Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  176] [ 3]  / answers: 1 / hits: 9440  / 3 Years ago, thu, july 15, 2021, 12:00:00

So, I am making a login form and I have already implemented the fetch API




const form = {
email: document.querySelector(#signin-email),
password: document.querySelector(#signin-password),
submit: document.querySelector(#signin-btn-submit),
messages:document.getElementById(form-messages)
};
let button = form.submit.addEventListener(click, (e)=> {
e.preventDefault();
const login = 'https://ffcc-app.herokuapp.com/user/login';

fetch(login, {
method: POST,
headers: {
Accept: application/json, text/plain, */*,
Content-Type: application/json,
},
body: JSON.stringify({
email: form.email.value,
password: form.password.value,
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => {
console.log(err);
});


});




I am also getting the desired output:
This


The problem is I have to redirect to the main page when 'login successful' else I have to display a message saying 'user does not exist'. how should I do that? What else should I add to my code?


More From » ajax

 Answers
8
const form = {
email: document.querySelector("#signin-email"),
password: document.querySelector("#signin-password"),
submit: document.querySelector("#signin-btn-submit"),
messages: document.getElementById("form-messages"),
};
let button = form.submit.addEventListener("click", (e) => {
e.preventDefault();
const login = "https://ffcc-app.herokuapp.com/user/login";

fetch(login, {
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: form.email.value,
password: form.password.value,
}),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
// code here //
if (data.error) {
alert("Error Password or Username"); /*displays error message*/
} else {
window.open(
"target.html"
); /*opens the target page while Id & password matches*/
}
})
.catch((err) => {
console.log(err);
});
});

login sucess and error handled by data.error as mentioned in your screenshot
👉 https://i.stack.imgur.com/WJBh2.png


[#1098] Thursday, July 8, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
;