7

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nisanth Kumar
  • 5,667
  • 8
  • 33
  • 43

2 Answers2

15

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
  • 338,112
  • 86
  • 474
  • 445
  • 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 Feb 16 '10 at 20:52
  • 1
    @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 Feb 16 '10 at 23:09
-5

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"

Frenchi In LA
  • 3,139
  • 3
  • 25
  • 41