What happens if an alert window is shown during an ajax call? - javascript

I was just wondering what could happen if, while an ajax call is being executed, an alert is prompted to the user, in the browser window.
Let's say, for example, that I have an ajax call
$.ajax({
url: ...,
type: GET/POST,
...
success: function(data){
console.log(data);
},
error: ...
});
that takes long time to complete (10 sec). While the call is executed, a simple javascript alert is thrown
alert("hello!");
What happens for example if:
ajax call starts
ajax call fetching data
alert is shown
ajax call returns data (alert window is still open!)
Knowing that JS is single threaded I know that the script execution will halt, I was just wondering what happens to the ajax call/response if the alert window is not closed "in time".
I hope I was clear enough and that this is not a "dummy" question. Thank you

This isn't exactly hard to try and see... but the answer is that the alert will take priority and hold up the flow of execution.
Upon closing the alert, and assuming the AJAX request has completed while the alert was open, then the success function will be processed (or error function).
Note that the AJAX request will continue to run while the alert is shown (so a long running AJAX can process while the alert is open), but it is just that your script cannot continue handling the request until the alert is closed.
Here is a working example, notice that the data isn't written to the console until the alert is closed.
Another point to be aware of is that after the alert closes, the script will continue with the rest of the function (the code immediate after the alert) before the AJAX response is handled. This helps demonstrate what I mean

The HTTP request will continue to run and be processed in the background.
When the JS event loop becomes free, the readystatechange handler will fire.
Some intermediate ready states may be skipped because the event loop was busy while that state was true.

Related

Wicket : How to refresh/redraw a wizard onSubmit?

I have a Wizard(org.apache.wicket.extensions.wizard.Wizard) that has an AjaxButton as its Next Button.
I am performing a long running operation on onSubmit() method of next button.
Before exiting from the method I am using ajaxTarget.appendJavascript(js) where ajaxTarget is AjaxRequestTarget and js is a JavaScript snippet that I want to be evaluated.
Now, as far as I know, this script won't get executed until `onSubmit()ยด has returned and the response is send back to the browser.
How can I execute my JavaScript immediately without waiting for onSubmit to have finished?
Note: I am using Wicket-4
this script won't get executed until the wizard is redrawn/refreshed.
All appended JavaScript snippets are executed once the AjaxRequest has finished - the wizard itself does not need to be updated.
If you're executing a long running task from your Ajax request, the browser's Ajax request will eventually run into a timeout.
You should move your long running task onto a separate thread.

jQuery: How to call a function before unload window

I want to call a function before closing a window.
For example I want to call ajax before closing page. I am using following code but its not working.
$(window).bind('beforeunload', function(){
$.ajax({
url:'logout.php',
type:'POST'
});
});
What is the best way to call function before closing the window?
You code is most likely being run, but as it starts a asynchronous ajax request and the browser tears down the page immediately after triggering onbeforeunload, the request probably never gets sent (or if it gets sent, probably gets aborted).
The event handler for onbeforeunload is only allowed to do a very limited set of things (and the list varies from browser to browser, and the list frequently changes as browsers update things). For that reason, using onbeforeunload for anything other than the one purpose for which it was intended, giving you a last ditch chance to warn the user of losing information by leaving the page, is not a good idea.
The code you have written just makes an ajax call, but even before the call can be made, your window will be exit. And even if the request is sent, it may be aborted in between.
Try this code:
function WinClose() {
$.ajax({
url:'logout.php',
type:'POST'
});
return false;
}
window.onbeforeunload = WinClose;
Write this code in <head>

Show a popup div when talking to AJAX server

I'm trying to show a popup in the middle of the screen while my website talks to my AJAX server. Since some of the operations take a couple seconds to do, I want to give my users a visual cue that an operation is occurring. For example, you can create a music playlist on my site. When the playlist is being created, I want a div to popup saying it's creating the playlist on my servers.
I made a jsfiddle to show the functions I'm using to try to produce this, but I'm having a bit of an opposite effect. In the fiddle, it shows the popup after it tries to talk to the server (it will fail to talk to the server because I deny anything outside my domain), but since it fails to talk to the sever, it never calls hide_popup().
On my servers, it never even shows the popup (unless I call an alert() directly after the show_popup() call).
I'm not sure why this happens, but I simply want to
1. Show the popup
2. Execute my AJAX-call
3. Hide the popup
Any suggestions?
There are a few problems with the way you wrote your code. Here are a couple of them:
(1.) Call:
var response = get_server_response("action=createPlaylist&name=" + name, false);
You are expecting a response immediately which will not happen with an AJAX call. Moreover, you are passing false for the async parameter, which is making it effectively a sync call. This is why your code is just waiting before doing anything else.
(2.) Implementation:
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
response = xmlhttp.responseText;
}
}
xmlhttp.open("POST", ajax_server, async);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(url);
return response;
You are only caching the result in response and not processing it while tracking onreadystatechange. You are actually processing it just after the call which will execute after the call and not on receiving the response. No need to return the response here.
(3.) popup:
You are not using show/hide at an appropriate place.
Solution:
I would suggest you fire a callback while tracking the onreadystatechange by implementing a function. Show the popup just before you make the network call. Hide it inside your callback function depending on the readyState and status.
Here is a working fiddle for you: http://jsfiddle.net/nDNXc/549/
Hope that helps.
First I recommend you to use a common library for your Ajax calls, e.g. jQuery.ajax.
Second learn about asynchronous Javascript. Your call of get_server_response() returns immediately without waiting for your Ajax request to complete. Have a look at the complete parameter in jQuery.ajax. It accepts a function that is called when your requests completes - the right place to hide your message!

state of XMLHttpRequest Object in jquery AJAX

In traditional javascript AJAX, we know if readystate is:
0 - The request is not initialized
1- The request has been set up
2 - The request has been sent
3 - The request is in process
4 - The request is complete.
When it comes to jQuery AJAX, we have:
complete property where we code what should happen after completion
success property where we code what should happen if the ajax request succeeds and
error property where we code what should happen if ajax request fails.
All of the above properties lets us code to do something after completion of ajax request. Where can I specify some code to execute something during processing(when readyState is 3) in Jquery Ajax??
As my AJAX script takes too long time to execute, which means, I will not attain 'complete' stage quickly. This seems like nothing is happening to the user. I wanted to initiate another ajax script at processing stage which gets information from server meanwhile and shows the user what has been done so far. Is it possible at all in Javascript? I know there is no multi-threading in Javascript.
I think I made my self clear. But, Please let me know if anything is not making any sense.
I handle this by initiating the first long running request, returning to the user immediately and allowing the process to fork server side for the extended processing.
The initial return ajax call to the user sets them up to 'watch' that process via a flag against the object ( I store them against the object in the database, but you could for instance watch file sizes or other stuff )
Subsequent ajax calls occur in a loop, each one returning setTimeout for the next call, and report on changes to that flag so the progress of the long running process is then visible. Completion of the long running process prompts NOT sending another setTimeout() and showing the overall results.
If your process is not that intensive, a simple spinner would probably do the job and no work for your server process. I usually handle that having $.ajax flip the visibility of a 'spinner' icon that's preloaded on my pages in the same spot for all.
According to jQuery's Ajax documention, they do not expose the readystate change event:
No onreadystatechange mechanism is provided, however, since success,
error, complete and statusCode cover all conceivable requirements.
It would be possible to show a loading image after the initial Ajax request is kicked off (and before getting any "complete" or "success" events, and then start polling a different URL via ajax which will give you the status of the first request, assuming your server can show progress of the long process before it completes.

jQuery.post callback not executing

When I make a call with jQuery.post, the callback is not being executed, but only if the call is made in a js file loaded into the webpage. If I copy and paste the same call into the javascript console of the browser, the callback get's executed. I know that the function is being called, because if I replace the call to jQuery.post with a simple alert(), it shows up. I've made sure the post request is completing (data is inserted into db on server side). I've also made sure that it is returning with a 200 code.
Also, this function is being called on demand when I click a button, so the DOM should be fully loaded by then.
Why would this be executed properly from the console, but not from a js file?
The problem ended up being that I wasn't returning false from the onclick callback, and so the page was refreshing every time I submitted the form. The refresh happened so fast that I didn't notice. If I moved the submit button out of the form, or returned false from the onclick callback, the expected behaviour occurred.

Categories