0

I'm trying to send an JSON-encoded data string to a remote machine using AJAX. Whenever I try to send the data string to the remote machine, one of two error messages will occur:

XMLHttpRequest cannot load http://10.1.0.139:8000/. 
No 'Access-Control-Allow-Origin' header is present on 
the requested resource. Origin 'http://localhost' is 
therefore not allowed access.

This message occurs when the remote machine is powered on and accepting connections. However, although I am getting this error, my code is working exactly as I want it to - as in, the remote machine receives the correct piece of data.

POST http://10.1.0.139:8000/ net::ERR_CONNECTION_REFUSED

And this message occurs when the remote machine is either powered off or does not have it's own server running that accepts incoming requests and connections.

The problem is, I want to be able to differentiate between these two error messages, and I do not know how. I can't use AJAX callbacks such as error() or fail(), because there will always be an error - and it will say that there has been a failed request despite a HTTP status of 200 suggesting that everything is okay (when the first error message shows).

Is there a way that I can do something similar to a Pseudo command of 'IF I FAIL TO CONNECT TO REMOTE MACHINE, DO...'

EDIT

Something I've noticed just now is that my remote machine does not display incoming connections from Internet Explorer - instead it displays this:

XMLHttpRequest: Network Error 0x2efd,   
Could not complete the operation due to error 00002efd.
Community
  • 1
  • 1

1 Answers1

0

Use the XMLHttpRequest timeout

var xhr = new window.XMLHttpRequest();
var data = 'x=1';
xhr.open('POST', 'http://10.1.0.139:8000/');
xhr.timeout = 5000;
xhr.addEventListener('timeout', function(e) {
   // handle dead server 
   console.log('timeout');
   console.error(e);
});
xhr.addEventListener('error', function(e) {
   // handle error - CORS probably in this case
   console.log('error');
   console.error(e);
});
xhr.addEventListener('load', function(e) {
   // handle success
   console.log('load');
   console.info(e);
});
xhr.send(data);

This triggers error in the case of a CORS error, and timeout in the case of no server

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87