0

I'm using an Ajax call to make a POST request, and a call is subsequently made to an API. The result is then returned. I was originally using the success callback which was firing, but then for some reason it stopped working, and I read that it has been replaced with done, so I tried changing it. I don't know why, but now neither done nor success will fire.I updated the browser recently, so maybe that has something to do with it. I'm also running it within Wordpress. 200 is being returned in the network tab, with the status and message encoded as JSON. The jQuery version is 1.12.4. Although the Ajax call completes, there is nothing logged in console, and the dialog doesn't open. How can I get this to work?

$.ajax({
  type: 'POST',
  dataType: 'json',
  url: ajax_object.ajax_url,
  data: {
    'action': $action,
    'product_id': $product_id,
  },
  success: function(data) {
    console.log(data.message);
    $( "#dialog" ).text(data.message);
    $( "#dialog" ).dialog( "option", "title", "API - " + data.status );
    $( "#dialog" ).dialog("open");
  }
  });

$.ajax({
  type: 'POST',
  dataType: 'json',
  url: ajax_object.ajax_url,
  data: {
    'action': $action,
    'product_id': $product_id,
  }
}).done(function(result) {
    console.log(result.message);
    $( "#dialog" ).text(result.message);
    $( "#dialog" ).dialog( "option", "title", "API - " + result.status );
    $( "#dialog" ).dialog("open");
  });
Matts
  • 1,301
  • 11
  • 30
  • what says the error log? error: function(jqXHR, textStatus, error){ console.log(jqXHR, textStatus, error) } – Michi Jul 02 '19 at 09:34

1 Answers1

1

Remove the dataType parameter from your jQuery, the JSON conversion that AJAX uses before trigger .done() its failing because something is missing/error in the JSON from the API. You could check it by adding .fail() after .done() and you will see how it triggers with the error.

$.ajax({}).done().fail(error => console.log(error) 

jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.

Ajax request returns 200 OK, but an error event is fired instead of success

Josep Vidal
  • 2,580
  • 2
  • 16
  • 27
  • Thanks, some other text is displayed before the message. It was some debugging info, and I didn't realise that this was affecting the response. When I removed it, it started working again – Matts Jul 02 '19 at 09:59