Search code examples
javascripthtmljsonxmlhttprequest

Http status not triggering on try and catch javascript


I have function to post JSON to an API end point which is working fine. This is my code.

function sendValuesPageLoad(){
     var xhr = new XMLHttpRequest();
     xhr.onreadystatechange = function () {
        try {
          if (xhr.readyState === 4 && xhr.status === 200) {}
        } catch (ex) {
            alert('Error parsing response.');
        }
     }
     try {
        xhr.open("POST", "test.html?"+encodedString, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send();
     } catch (ex) {
        xhr.open("POST", "error.html?"+encodedString, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send();
     }
} 

What i'm trying to achieve is to perform further action if the xhr.status is not equal to 200.

But the catch is not being triggered.

Can anyone please help on this?

Thanks in advance.


Solution

  • function sendValuesPageLoad(){
       var encodedString = "value=2";
    
       var xhr = new XMLHttpRequest();
       console.log('UNSENT: ', xhr.status);
    
       xhr.open("POST", "test.html?" + encodedString, true);
       console.log('OPENED: ', xhr.status);
       
       xhr.onprogress = function () {
         console.log('LOADING: ', xhr.status);
       };
       
       xhr.setRequestHeader("Content-Type", "application/json");
       
       xhr.onload = function () {
         console.log('DONE: ', xhr.status);
         
         if(xhr.status === 200){
            alert("Status code is 200");
            
         }else{
             alert("Status code is not 200, but " + xhr.status);
         
            xhr.open("POST", "error.html?"+encodedString, true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.send();
         }
       };
       
       xhr.send();  
    }
    
    sendValuesPageLoad();