Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to make an AJAX call that doesn't need a response?

Is there a proper way to make an AJAX call when I don't want a response back from the server? I want the server to save some data, but the client doesn't need a response. If the server never responds, will the AJAX connection remain open, waiting for a response until it times out?

I would use Javascript like the following. It's a typical AJAX call except I left out the xmlhttp.onreadystatechange event.

function SaveLabel()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert('Your browser does not support this feature.');
        return;
    }

    xmlhttp.open('GET', 'mypage.aspx?label=1');
    xmlhttp.send(null);
}

I found a similar question, but it doesn't really answer mine: Does Ajax connection disconnect at some point?

like image 395
NJS Avatar asked May 22 '12 05:05

NJS


2 Answers

You need to keep the connection open until the server is done with it, regardless of whether or not you expect (or will be or won't be) a reply from the server.

The reason is that most webservers will kill requests if the client disconnects before the script has finished executing.

The server doesn't have to "respond" as in return data, it just needs to "return".

i.e. in answer to your question "Does Ajax connection disconnect at some point?": Yes, when the server terminates the connection.

So what you need to do is make sure that your ASP(X) script terminates as soon as it has finished its work. Don't let it run forever, pass data to a helper daemon/service, etc. that will need long-running processing.

like image 120
Mahmoud Al-Qudsi Avatar answered Sep 30 '22 04:09

Mahmoud Al-Qudsi


xmlhttp.onreadystatechange is just an event of the XHR object where you attach a listener to listen for it's changes in state. It's synonymous to having a button on the page and adding an onclick handler.

It does the same thing with or without a handler (AJAX still calls, the button is still clickable). The only difference is that you don't know what just happened (You don't know if AJAX succeeded/failed, you don't know when the button was clicked).

like image 40
Joseph Avatar answered Sep 30 '22 03:09

Joseph