Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX - Receiving the response after user changes pages

What I know:
When I make an ajax call to my server, a handler is created, the request is sent, my php script receives the request and processes it and--if I tell it to--sends back a response, which my javascript parses as I require. I also know that php will continue to process the request even if the user closes the browser or changes pages (its all being done on the server side, so why wouldn't it? ^.^).

What I need to know:
Is the ajax handler killed when the user changes pages within my site? For example: The user is on mysite.com/foo.php. They click a link that sends off an ajax request to my server. The response of that request is to be shown in div#resp on foo.php. They then navigate to mysite.com/bar.php before the response is received.

If I load the same javascript functions and have the needed div#resp element on bar.php, can the javascript function that called the ajax still receive the response from the server and pass it into the div#resp on bar.php, thus showing the response? Or is the original ajax handle no longer available? And if it is no longer available in standard javascript, is there some implantation in jQuery that will allow me retrieve the response and show it on bar.php?

like image 433
Cameron Oakenleaf Avatar asked Oct 06 '12 01:10

Cameron Oakenleaf


3 Answers

From what you're describing, no - once you navigate to another page and cause a page reload, all of your javascript handlers are re-instantiated and the original ones destroyed.

like image 72
codewrangler Avatar answered Oct 20 '22 23:10

codewrangler


The answer is no. When you change page, the javascript process is killed and restarted. Nothing stays between page reload.

Although, if your page also change in ajax, then the process isn't killed, and you could receive the response. (BTW, this could be made mostly seamless to the final user with PushState in recent browser)

like image 5
Simon Boudrias Avatar answered Oct 20 '22 22:10

Simon Boudrias


No, you are not guaranteed to have your XHR (AJAX) response back before the user navigates away to the next page.

If you want to be able to detect, server-side, when a user leaves your page, you would have to use WebSocket's or a similar technology. A WebSocket connection is a long-running connection to a foreign host which you can easily detect server-side when it is severed. https://github.com/sockjs is an example of a WebSocket client + server.

If you simply want to display something to the user before he/she navigates away from the page you need to look at window.onbeforeunload - onbeforeunload fires before the user leaves the page, but will not allow you to do any async AJAX requests. For more info see https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload

like image 2
bjornl Avatar answered Oct 20 '22 22:10

bjornl