Reputation: 131
I am trying to create a login page for the first time with ajax, but it isn't properly working. I have a login HTML that lets the user input the username and password with a submit button that calls the javascript script when it is clicked. When the proper password displayed below is entered I would like for it to go to the home html page, but nothing happens when I type in the password seen below. I could attach the HTML code if it would be helpful, but I think that it is a problem with this code as I get an error of: POST http://localhost:5000/login 404 (NOT FOUND). How would I properly change the code to make sure that I would be able to get to the home page?
$("#submit").click(function(){
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
method:'POST',
url:'http://localhost:5000/login',
data: {
username: username,
password: password
}
}).done(function (data) {
if(data.username == "user" && data.password =="pass"){
window.location.href = "home.html";
}
else{
alert("Invalid Credentials");
}
});
});
});
Upvotes: 0
Views: 120
Reputation: 30893
Consider something like the following.
function login(u, p) {
var r = false;
$.post("http://localhost:5000/login", {
username: u,
password: p
}, function(data) {
if (data.username == "user" && data.password == "pass") {
r = true;
}
});
return r;
}
$("#submit").click(function(e) {
$(this).closest("form").trigger("submit");
}
$("#submit").closest("form").submit(function(e){
e.preventDefault();
var username = $("#username").val();
var password = $("#password").val();
var result = login(username, password);
if (result) {
window.location.href = "./home.html";
} else {
console.log("Login Error");
}
});
Considering that you may be using a login form, you may want to bind to the submit
callback instead. You can put the Ajax call into it's own function to make it a little easier to use. If there is a successful login, you can perform the redirect.
Upvotes: 1