Is it possible to send an jQuery.ajax call or equivalent without any sort of response? I want to trigger something on the server as I leave the page with the onbeforeunload command, but it's not something I need to feedback to the client, so I just want to send off the command and not wait for a response.
Is that possible?
Is it possible to send an jQuery.ajax call or equivalent without any sort of response? I want to trigger something on the server as I leave the page with the onbeforeunload command, but it's not something I need to feedback to the client, so I just want to send off the command and not wait for a response.
Is that possible?
Share Improve this question asked Sep 20, 2012 at 18:08 Paul TomblinPaul Tomblin 183k59 gold badges323 silver badges411 bronze badges 3 |4 Answers
Reset to default 15Every request has a response. Even if the server throws an error a response is coming back with the error.
You can ignore the response if you like to just don't add a success
callback.
$.ajax({
url: "theURL",
data: theData
});
You could use the navigator sendBeacon API mentioned referenced in this stack overflow answer or directly linked to here.
From the description on the site, it asynchronously sends off some data and just checks if it was able to queue the data for sending or not. The unload handler shouldn't ignore the request like it might do with other asynchronous XMLHttpRequests.
navigator.sendBeacon(url, data) - The sendBeacon() method returns true if the user agent is able to successfully queue the data for transfer, Otherwise it returns false.
...
ensuring that the data has been sent during the unloading of a document is something that has traditionally been difficult for developers, because user agents typically ignore asynchronous XMLHttpRequests made in an unload handler.
Assuming you're using something like this:
$.ajax({
url: "test.html",
context: document.body
})
(borrowed from http://api.jquery.com/jQuery.ajax/
and edited), you can discard the response.
If you are trying to return a response as soon as possible I think that is more of a server architecture decision. You can offload the actual work the request involves to a broker or something so you can return to the user as soon as possible? I don't think sending just a one way message is feasible
success
handler (though may like to include thefailure
handler to know if it went right or not). Just send the required data and let the server-side script do its duty. – NedStarkOfWinterfell Commented Sep 20, 2012 at 18:11