-1
const http = new XMLHttpRequest();
const url = 'http://192.168.1.10/';
http.open('get', url, false);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onload = function () {
    if(http.status === 200 || http.status == 0) {
         alert("succeed")
    } else {
          alert("failed")
    }
}
http.send();

why although it didn't get http.status === 200 it didn't alert failed !

image1

image2

Dor-Ron
  • 1,787
  • 3
  • 15
  • 27
mooooooon
  • 23
  • 1
  • 7
  • Can you try to use `https://www.google.com/` instead of `http://192.168.1.10/`, do you try to connect yourself with your browser at this address ? Is it working ? – Benoit Chassignol Jun 24 '19 at 23:41
  • @BenoitChassignol i am doing this Intentionally .. to see if the else would work if anything unexpected happened !!! but it didn't – mooooooon Jun 25 '19 at 15:20
  • It didn't works cause the address doesn't exist, it's not a response from the server but an error coming from the browser, you dont have status return. – Benoit Chassignol Jun 25 '19 at 17:51

3 Answers3

1

Update: The server may be offline, and OP want to retry when Ajax request is timed out.

To "fix" this issue, you can wrap http.send() statement into a try-catch block, such as:

...
try {
  http.send();
} catch(e) {
  //e.name would be "NetworkError" if the server is offline.
  console.log(e);
}

If "NetworkError" is caught, server-offline is detected, and Ajax request can be retried some time later.


There are 3 problems in this issue:

  1. According to the error screenshot (net::ERR_CONNECTION_TIMED_OUT), the target server (http://192.168.1.10/) does not respond. Please check whether it is accessible.

  2. In the code, the Content-Type is defined as application/x-www-form-urlencoded, which means a form is submitted. However, the Ajax request is a GET request without any data-sending logic. It is a pretty weird combination and can be refused by browser or server side logic. If you just want to play with Ajax GET request, it is not necessary to configure Content-Type.

  3. The load event (http.onload in the question) of XMLHttpRequest is not supported well, please use onreadystatechange suggested by @Katie.

shaochuancs
  • 15,342
  • 3
  • 54
  • 62
  • i am doing this Intentionally .. to see if the else would work if anything unexpected happened !!! but it didn't ... and http.onreadystatechange didn't make a difference !! – mooooooon Jun 25 '19 at 15:23
  • Do you own 192.168.1.10? Does it exist? If yes, does it receive the HTTP request? – shaochuancs Jun 25 '19 at 22:01
  • Well, that’s why you didn’t get the http status. Instead, you get timeout error from browser. – shaochuancs Jun 25 '19 at 23:26
  • yes i want it retry "if anything unexpected happened" just like the timeout error ... but what it's called if it's not a http status ? – mooooooon Jun 26 '19 at 00:39
  • 1
    Nothing is invoked here. `http.onload` is not triggered at all, as there is nothing loaded. There are two types of "timeout error": 1. Timeout error because browser cannot connect to the server. 2. Timeout error because server takes too much time (but server itself is connected) -- you can only listen to the 2nd type of time out error. If the server itself does not exist, nothing will be called. – shaochuancs Jun 26 '19 at 00:46
  • so what do you suggest to fix that ? the first type of it? "If the server itself does not exist" let's say that the server is down for an unknown amount of time and i want it to retry till it comes working again ! – mooooooon Jun 26 '19 at 01:17
  • You can wrap `http.send()` into a `try-catch` block. Please check my answer update. – shaochuancs Jun 26 '19 at 01:41
  • I am agree with @shaochuancs that's what I am trying to telling you but he had a better explanation about the error and how you can fix it. Just keep in mind that, you can't have a http response when the address doesn't exist. You don't get a response from the server, you get it from the browser so you can't treat it in the same way that you gonna treat an http response, cause the last one gonna return you an httpResponse object, and the browser just throw you an error. – Benoit Chassignol Jun 26 '19 at 11:50
  • @shaochuancs thanks for the great answer .. but about "Ajax request can be retried some time later" how can i do that ? i tried it [link](https://www.pastiebin.com/5d1385c264301) but it didn't console log anything although "net::ERR_CONNECTION_TIMED_OUT" and it alerted failed .... and even when the server status is 200 it still alerts succeed then "failed" twice ! – mooooooon Jun 26 '19 at 15:01
  • You can use `setTimeout` in `catch` block. – shaochuancs Jun 26 '19 at 21:45
0

You could try to catch the error using onreadystatechange like this:

const http = new XMLHttpRequest();
const url = 'http://192.168.1.10/';
http.open('get', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.setRequestHeader("Access-Control-Allow-Origin:", "*");
http.setRequestHeader("Access-Control-Allow-Methods", "GET,POST,PUT");
http.onreadystatechange = function (oEvent) {  
    if (http.readyState === 4) {  
        if (http.status === 200) {  
           console.log(http.responseText);
           alert("succeed");
        } else {  
           console.log("Error", http.statusText); 
           alert("failed");
        }  
    }  
}; 
http.send();

Taken from the documentation here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange

Katie
  • 45,622
  • 19
  • 93
  • 125
  • no it didn't work "Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load" @Katie – mooooooon Jun 24 '19 at 23:39
  • Hey @mooooooon ! I updated the code - give it a try, hopefully it works this time! – Katie Jun 25 '19 at 00:03
  • it still doesn't work !!!!!!! and Uncaught TypeError: http.setHeader is not a function btw Allow-Origin isn't the case !! – mooooooon Jun 25 '19 at 15:23
  • it works now i removed these lines `http.setHeader("Access-Control-Allow-Origin:", "*"); http.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT");` can you explain what did you add to make it work ? – mooooooon Jun 25 '19 at 15:28
  • how can i now make it retry the request after 1 second if it failed ? i tried to put the full xmlhttp request in a function then call it back and in the else part i call it again but i got this "Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 192.168.1.10" the code https://www.pastiebin.com/5d124d28e45d0 and how can i do it if i have more than one request that depends on each other !! – mooooooon Jun 25 '19 at 16:35
  • Hey @mooooooon ! I think the key to get it working was setting the "async" param in http.open to `true`. In order to retry the request after 1 second, you could try wrapping this all up in a function, then calling itself using `setTimeout`. See https://stackoverflow.com/questions/32878613/networkerror-failed-to-execute-send-on-xmlhttprequest/32878672 – Katie Jun 25 '19 at 18:06
  • i tried but setting "async" param in http.open to true" mess the reset of the code !! Uncaught TypeError: Cannot read property '1' of null – mooooooon Jun 25 '19 at 19:45
0

just use XMLHttpRequest.onerror function it was made for such Situations. but you may need to use Asynchronous request (true) .

const http = new XMLHttpRequest();
const url = 'http://192.168.1.10/';
http.open('get', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onload = function () {
    if(http.status === 200 || http.status == 0) {
         alert("succeed")
    }
}
http.onerror = function () {         
        alert("failed")
};
    http.send();
mooooooon
  • 23
  • 1
  • 7