Sergey Telshevsky
Sergey Telshevsky

Reputation: 12197

Server XHR got received event in JS

Situation:

Target API is external and may not be changed in any way. I have a JS client that sends some data to the API on client button click. Something like

$.ajax({
    type: "POST",
    url: "http://api.url/some_resource",
    data: {name: 'John', email: '[email protected]'}
}).done(function(msg) {
    if (msg === 'ok') {
        alert('Your Callback Request Sent!');
    } else {
        alert('Error occurred. Please try later.');long
    }
});

When I send the request I have to wait to receive the response from the server to see if it was successful and notify the client if it was or was not.

The problem is that I the API is friggin slow and does not reply directly that it received everything and will process the request, but instead is trying to do all the job like sending email and only then replying. Sometimes it takes about 20s for response to be received (the XHR request response).

Is it possible (jQuery or pure JS) to fire something like "request reached server event" so I would be at least sure there were no connection problems?

Upvotes: 0

Views: 53

Answers (1)

Bergi
Bergi

Reputation: 664548

Is it possible to fire something like "request reached server event"

No - the client does not know of that event. It only knows a) when it has sent the last bit of the request and b) when it has received the first bit of the response. There is nothing in between but waiting.

To the XMLHttpRequest interface there is the following readyState information available:

Val State            Description
---------------------------------------------------------------------------------
0   UNSENT           open()has not been called yet.
1   OPENED           send()has not been called yet.
2   HEADERS_RECEIVED send() has been called, and headers and status are available
3   LOADING          Downloading; responseText holds partial data.
4   DONE             The operation is complete.

so I would be at least sure there were no connection problems?

Well, if there had been connection problems that are detectable to the client, you would've been notified of them.

Upvotes: 1

Related Questions