Can I make use of jQuery AJAX API and make a synchronous calls?
jQuery Synchronous Calls – How to Make Synchronous Calls with jQuery
ajaxjquerysynchronous
Related Solutions
As you're making a synchronous request, that should be
function getRemote() {
return $.ajax({
type: "GET",
url: remote_url,
async: false
}).responseText;
}
Example - http://api.jquery.com/jQuery.ajax/#example-3
PLEASE NOTE: Setting async property to false is deprecated and in the process of being removed (link). Many browsers including Firefox and Chrome have already started to print a warning in the console if you use this:
Chrome:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
Firefox:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/
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;
}
Best Answer
Like Obama would say: YES YOU CAN !
jQuery .ajax()
Setting
within the .ajax() handler will do the trick.