Carl Beech
Carl Beech

Reputation: 11

jquery AJAX call - why do success and failure go to the same output location?

ok, I may be missing something simple...

Got a jquery ajax call:

M_DATA = some data;
$.ajax({
  url: "some url..." + M_DATA.id,
  data: M_DATA,
  type: "post",
  timeout: 5000,
  success: function(response, textStatus, xhr) {
    console.log("AJAX result: " + response + "; status: " + textStatus);
    //alert("AJAX result: " + response + "; status: " + textStatus);
  },
  error: function(XMLHttpRequest, textStatus, error) {
    alert("AJAX error: " + textStatus + "; " + error);
  }
});

If I set 'success' to output to the console, then the 'error' function also outputs to the console, even though I've requested an alert function to have a popup...

If I set 'success' to use the alert function, then the error also uses the alert function as well...

What I want is for success to output to the console, and error to output an alert...

So not sure what I'm doing wrong here... anyone any thoughts? Thanks Carl.

I've tried switching the two (i.e. console.log and alert) within the success function and the error function appears to follow suit...?

Upvotes: 0

Views: 37

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76943

From the question description it is clear that your expectation was that the success and the error will be executed. So I understand the reason of the confusion that you had and hence my answer is this.

Basically, you are sending an AJAX request via jQuery to the server. You have a success and an error callback, but only one of them may be executed. Let me elaborate:

  • if the request has success status (that is, HTTP status code is 200, which means okay) then the success callback will be executed
  • if the request has an error status, then the error callback will be executed

So in order to test the error status, test with an end point that does not exist, or one that does not work, or induce a temporary error into the endpoint you tackle for the purpose of the test.

Bottom line: success and error are mutually exclusive, so if one of them is applicable, then the corresponding callback will be executed, but not the other one.

Upvotes: 0

Related Questions