How to make JQuery-AJAX request synchronous
From jQuery.ajax()
async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
So in your request, you must do async: false
instead of async: "false"
.
Update:
The return value of ajaxSubmit
is not the return value of the success: function(){...}
. ajaxSubmit
returns no value at all, which is equivalent to undefined
, which in turn evaluates to true.
And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.
If you want to submit the form only, when the response is "Successful"
, you must return false
from ajaxSubmit
and then submit the form in the success
function, as @halilb already suggested.
Something along these lines should work
function ajaxSubmit() {
var password = $.trim($('#employee_password').val());
$.ajax({
type: "POST",
url: "checkpass.php",
data: "password="+password,
success: function(response) {
if(response == "Successful")
{
$('form').removeAttr('onsubmit'); // prevent endless loop
$('form').submit();
}
}
});
return false;
}
It's as simple as the one below, and works like a charm.
My solution perfectly answers your question: How to make JQuery-AJAX request synchronous
Set ajax to synchronous before the ajax call, and then reset it after your ajax call:
$.ajaxSetup({async: false});
$ajax({ajax call....});
$.ajaxSetup({async: true});
In your case it would look like this:
$.ajaxSetup({async: false});
$.ajax({
type: "POST",
async: "false",
url: "checkpass.php",
data: "password="+password,
success: function(html) {
var arr=$.parseJSON(html);
if(arr == "Successful") {
return true;
} else {
return false;
}
}
});
$.ajaxSetup({async: true});
I hope it helps :)