Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use jQuery to fire an AJAX request from an unload event handler?

I have the following code, intended to log the event when a user closes a chat window:

$(window).unload( function() {
   test();
});

function test()
{
   alert("Hi");
   $.ajax({
      type: "POST",
      url: baseUrl + 'Index/test',
      data: "user_id=" + "Nisanth" + "& chat_id=" + 2,
      success: function(msg){
         alert(msg);
      }
   });
   alert('Success');
}

Both the "Hi" and "Success" messages alert fine but the alert in the AJAX callback doesn't... The operation I intend to trigger via the AJAX request is also not happening (I'm developing a chat application, and intend to log an entry in the database when the user closes the window).

like image 372
Nisanth Kumar Avatar asked Feb 16 '10 17:02

Nisanth Kumar


People also ask

Is jQuery required for Ajax?

On the client side, including jQuery is all you need to do to make ajax requests. If its not working, there is something wrong with either the way your server is configured or with the php script. See if your server is throwing any errors and go from there.

Which jQuery method registers a handler to be called when all Ajax requests have completed?

ajaxStop() Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.

How do I know if jQuery Ajax is working?

You can use the setTimout() method which will execute your action after your given time. But it is not a better solution. jQuery has the inbuilt event handler to detect AJAX completion.


1 Answers

Because the ajax is asynchronous, the page is unloading before the response is properly sent, effectively terminating the connection. Try setting async:false;, although this will delay unloading the page until after the response is received, which isn't great for user experience if your server is running slow.

$(window).unload( function () { 
    test(); 
}); 
function test() 
{ 
    alert("Hi"); 
    $.ajax({ 
    async: false,
    type: "POST", 
    url: baseUrl + 'Index/test', 
    data: "user_id=" + "Nisanth" + "& chat_id=" + 2, 
    success: function(msg){ 
            alert(msg); 
        } 
    }); 
    alert('Success'); 
} 
like image 88
Andy E Avatar answered Sep 18 '22 23:09

Andy E