Mariton
Mariton

Reputation: 621

How do you write an error message when an Ajax call is not successful in JavaScript?

I would like to display an error message if my Ajax call is unsuccessful. Simple enough but I cannot modify the Ajax function. I created an onClick listener that does a few things when my AJAX call is successful. I would just like to do something when the call is unsuccessful.

So If I decide to add:

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

Where would it be placed?

JSFiddle Example Here

My html is:

<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 is:

 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);
    };

Upvotes: 3

Views: 977

Answers (3)

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

Without modifying the function addUser(), the seemingly only possible way to do this would be modifying the XMLHttpRequest prototype, as suggested by this answer, to add an event listener for the readystatechange event (using addEventListener()). Also, the onerror function could be overridden to detect when an error causes an XMLHttpRequest transaction to fail.

Bear in mind that 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 plunker but it seems unlikely that will yield a response code other than 200. To test with failing XHR requests, try this PHPfiddle, where every other XHR request will yield a response code of 500.

Upvotes: 1

Hui-Jou Chou
Hui-Jou Chou

Reputation: 1

I guess this question is asking you to display an error message if the AJAX request return an error and you are not allowed to modify the addUser(). If you pay attention to see the addUser() function

addUser(username, email, callback)

inside this function, the code shows that they are mimicking a random failure situation as follows:

    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 callback function. The response will randomly show error or success. So, you don't need to modify 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
   }
}

Upvotes: 0

Mert Cengiz
Mert Cengiz

Reputation: 11

You can check xhr status and when it's not 200 then it was not succeed, Then You can Throw responseText.

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

Upvotes: 0

Related Questions