简体   繁体   中英

How to validate a username / password via JQuery / Ajax?

Trying to get this to work for sometime now:

<input id="usr_login_attp" value="ok" />

function check_for_acc() { 
 $("#usr_login_attp").val("ok");
 jQuery.ajax({
   url: "http://localhost:3000/login/validate_user/", 
   type: 'POST',
   dataType: 'json',
   data: {'email':$('#user_email').val(), 'password':$('#user_password').val(), 'authenticity_token': jQuery('input[name="authenticity_token"]').val()},
   error: function(xhr_data) {
     //sdfsd
   },
   success: function(xhr_data) {
     $("#usr_login_attp").val(xhr_data.status);
   }
 });
}

check_for_acc();
if ($("#usr_login_attp").val() == "fail") {
  err++;
  errStr += "Email or Password Was Not Recognized<br />";
}

The ajax function is updating the $("#usr_login_attp") field with either "ok" or "fail", this part is working ok, however when I call check_for_acc() , the following if statement fails to pass everytime, regardless of what the actual value of $("#usr_login_attp") is?

This is driving me nuts, can anyone see what I'm doing wrong here?

Yep! You're thinking that the success handler will execute before the rest of your script does. That's almost certainly incorrect.

The processing of the login success/failure needs to happen within the callback. Once you call check_for_acc() , it makes the Ajax call--but the callback doesn't get called until the Ajax call completes. Meanwhile, your code runs merrily along.

Alternatively, you could use the jQuery.when() function to wrap up some of that hoop jumping for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM