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).
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.
ajaxStop() Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.
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.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With