How do you write an error message when an Ajax call fails in JavaScript?

I want to show an error message if my Ajax call was unsuccessful. Simple enough, but I can't seem to change the Ajax function. I created an onClick listener that does several things when my AJAX call is successful. I just would like to do something when the challenge is unsuccessful.

So, if I decide to add:

 if (xhr.status !== 200) {
   //Error Message here
   }

      

Where will it be located?

JSFiddle example here

My html:

<div id="test-form">
      <h2>Add a User:</h2>
      <label for="Username:">
       <input id="username" type="text" name="username" placeholder="Type username here">
     </label>

      <label for="Email:">
      <span id='result'></span>
      <input id="email" type="email" name="email" placeholder="email">
      </label>
      <button id="myButton">add user</button>
      <h2 class="clear">Users:</h2>
      <ul id="users"></ul>
    </div>

      

My code:

 var el = document.getElementById("myButton");
    el.onclick = function() {
      addUser(username, email, onSuccess);
    }

    function onSuccess(result){
      var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

      var username = document.getElementById("username").value;
      var email = document.getElementById("email");
        var message = document.getElementById("result").classList;

      document.getElementById("users").innerHTML+= '<li>' + username +'</li>';

    if (!filter.test(email.value)) {
        document.getElementById('result').innerHTML+='Not a valid email';
        email.focus;
         return false;
     } else {


        message.add("hide");
      }

    }



    // Do not modify this function. Add user service wrapper.
    function addUser(username, email, callback) {
        var xhr = new XMLHttpRequest();
        var response;
        var success = (!!Math.round(Math.random()));

        if (!success){
            response = JSON.stringify({
                success: success,
                error: "Oups, something went wrong!"
            });
        } else {
            response = JSON.stringify({
                success: success,
                user: {
                    username: username,
                    email: email
                }
            });   
        }

        xhr.open("POST", "/echo/json/");
        xhr.onload = function () {
                if (xhr.status === 200) {
                    callback(JSON.parse(xhr.responseText));
            }
        }
        xhr.send("json=" + response);
    };

      

+3


source to share


3 answers


Without modifying the addUser () function, the seemingly only possible way to do this would be to modify the XMLHttpRequest prototype , as suggested by this answer , to add an event listener for the readystatechange event (using addEventListener () ). In addition, the onerror function can be overridden to detect when an error calls the XMLHttpRequest for a transaction.

Remember this would affect ALL XMLHttpRequests on the page!



var lastResponseCode, oldSendFunction;
// store the native send()
oldSendFunction = XMLHttpRequest.prototype.send;
// override the native send()
XMLHttpRequest.prototype.send = function() {
    //subscribe to ready state change events
    this.addEventListener("readystatechange", function(readyEvent) {
        //store the response code, to be checked later
        lastResponseCode = readyEvent.target.status;
    });
    // call the native send()
    oldSendFunction.apply(this, arguments);
}
function onSuccess(result) {
    if (lastResponseCode == 200) {
        //last request was successful
        //...
    }
    else {
         //other response was received - could have been 2xx,3xx,4xx,5xx
    }
}

      

This is saved in this updated plunger , but it seems unlikely that it will give a response code other than 200. To test with XHR request errors, try this PHPfiddle where every other XHR request will give a response code 500

.

+1


source


You can check the xhr status and when it is not 200 then it failed, then you can send a response text.



if (xhr.status !== 200)
    throw(xhr.responseText);

      

0


source


I assume this question asks you to display an error message if the AJAX request returns an error and you are not allowed to modify addUser (). If you pay attention to the addUser () function

addUser (username, email, callback)

inside this function, the code shows that they simulate a random failure situation like this:

    var success = (!!Math.round(Math.random()));
    if (!success){
        response = JSON.stringify({
            success: success,
            error: "Oups, something went wrong!"
        });
    } else {
        response = JSON.stringify({
            success: success,
            user: {
                username: username,
                email: email
            }
        });   
    }

      

so I think you can just check the response from the callback function. The answer will randomly show error or success. This way you don't need to change addUser () at all.

function onSuccess(result){
      //check your console to see what is the result first, so you can know how it works
      console.log(result);

      if(result.success){
       // do something
       }else{
       // display error message
   }
}

      

0


source







All Articles