Skip to content
Advertisement

Why does my ajax success callback-function not work as expected?

I code this ajax request but I don’t know why the code in the success method doesn’t work

Even though in the networks in chrome browser appear state: 200ok

img

this is ajax code:

$("#noti_filter").click(function(){
  //first add item into cart
  var item_id = 'test';
  $.ajax({
    method:"POST",
    //contentType:"application/json",
    url:"../html/notifies.php",
    data:{product_id:item_id},
    dataType: "json",
    success:function(data,state) {
      console.log(data);
      console.log(state);
      alert('ajax success');
    }
  });
});

the problem is that alert or console Not to mention the others code

  success:function(data,state)
  {
    console.log(data);
    console.log(state);
    alert('ajax success');

  }

Advertisement

Answer

From the ajax events docs:

success (Local Event)

This event is only called if the request was successful (no errors from the server, no errors with the data).

Since your server responded with 200 OK that means we can route out problems with the server and are left with errors with the data.

From the ajax docs (only the relevant parts):

dataType

The type of data that you’re expecting back from the server.

The available types (and the result passed as the first argument to your success callback) are:

“json”: Evaluates the response as JSON and returns a JavaScript object. … The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

So most likely the data returned by the server is being rejected by ajax in which case a parse error should be thrown.

This would be an example of how to implement an error handler:

$("#noti_filter").click(function(){
    //first add item into cart
    var item_id = 'test';

    $.ajax({
       method:"POST",
       //contentType:"application/json",
       url:"../html/notifies.php",
       data:{product_id:item_id},
       dataType: "json",
       success: function(data,state) {
           console.log(data);
           console.log(state);
           alert('ajax success');
       },
       error: function(err) {
           console.log(err.responseText);   // <-- printing error message to console
       }
    });
});
Advertisement