views:

135

answers:

2

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).

+4  A: 

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'); 
} 
Andy E
+1 *very* good to know.
Pekka
@Pekka: thanks :-)
Andy E
Thank u very much Andy E .. My problem solved :)
Nisanth
I'm curious - is there a handler for knowing when the request was sent? I know there is 'success', and 'complete', but I believe those only happen after the response has been processed. But for unload there is no need to wait for a response, you can leave as soon as you send the last char for the request.
Matt
@Matt: I think just the success/failure callbacks are provided by jQuery. However, a standard `XMLHttpRequest` has the `onreadystatechange` event which fires at different stages of the call. When the value of the `readyState` property is `2`, it means the data has been sent and headers are available. So you could keep it async and use a `while (xhr.readyState < 2)` loop. But if your server doesn't return any data the time difference would be minimal anyway.
Andy E
A: 

the problem is the format of your data. It is converted to a query string, it must be Key/Value pairs something like: "user_id:value"

FrenchiInLa
No. It can also just *be* a querystring. See: http://api.jquery.com/jQuery.ajax/
Shog9