I use the following code to send an action and parameter to a script on my server:
$(function() {
url = "http://...../myscript.php";
$.post(url, { action: 'my action', param: 'my parameter'}, {cache: false});
alert("Hello");
});
I noticed (on Safari 6.0.4 on MacOSX) the alert box pops up and the ajax request is only sent after I click "OK". (On Chrome the request is sent while the alert is displayed).
So the code following my ajax request actually delays the request being sent.
Why is this?
Edit:
$.post(url, { action: 'system', param: 'volume get 5'}, {cache: false});
sum = 0;
for(i = 0; i < 1000000000; i++)
sum++;
$("title").html(sum);
Causes the request to be sent after the calculation is done.
I noticed (on Safari 6.0.4 on MacOSX) the alert box pops up and the ajax request is only sent after I click "OK". (On Chrome the request is sent while the alert is displayed).
So the code following my ajax request actually delays the request being sent.
I find that very surprising, but I can't test it as I don't have Mac OS X. Although alert
blocks the main JavaScript thread, it shouldn't prevent the browser from sending the request, as the browser is multi-threaded. But I suppose it could, in some implementations.
Note that regardless, alert
will hold up the call to any "success" or "error" handlers you have associated with the request, which is a completely different thing. This is because unless you use web workers, JavaScript is single-threaded on browsers, and (again) alert
holds up the one JavaScript thread.
If the sending is really getting held up by the alert
, you can fix that with setTimeout
:
$(function() {
url = "http://...../myscript.php";
$.post(url, { action: 'my action', param: 'my parameter'}, {cache: false});
setTimeout(function() { alert("Hello"); }, 0); // Defers it
});
If it's the callbacks that are getting held up, the best way to deal with that is to do something more modern than an alert
, such as a nicely-styled absolutely-positioned div
containing the message. If you want the message to be modal, you can do that yourself although there are some edge conditions around disabling the rest of the page; but there are also about a million "modal" plug-ins for jQuery that handle those edge conditions for you. (Both jQuery UI and Bootstrap provide them, and there are lots of others.)