Hi Everyone!
I am trying to use a $.post call in jQuery to check a user's credentials before submitting a form (so I can show errors without reloading the page), but I've run into a problem. I know why it is, because AJAX is not synchronous, but I just can't figure out how to do it.
In my code the script I'm making the call to returns "valid" or "invalid". If the return is "valid", I want to submit the form, if not, show an error message. Here is a simplified version:
$("#my_form").submit( function () {
some_value = "username"
$.post(script_location, {data : some_value}, function (data) {
response = data
})
if (response == "valid") {
return true
}
else {
$(".error").show()
return false
}
})
This obviously does not work because code is executed quickly one after another and the variable "response" is not yet set when the execution gets to the if statement, since it is set sometime later, asynchronously.
I looked into using functions, callbacks, but nothing seems to work properly, I always run into the same issue. This is probably really simple, i just a complete dunce, please do let me know what is the standard way of doing this properly.