0

I have the following code as aprt of my .ajax section

success: function (data) {
    alert("success");
},
error: function(xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
}

The first alert never runs, however the data is submitted correctly using the below:

data: JSON.stringify({ "solution": JSON.stringify(data) }),  // Data is HTML

In fact, the second alert comes back with a status of 200 and everything through Google Chrome console looks fine.

Any idea? Full code:

var request = jQuery.ajax({
    url: "/answers/"+content_id,
    type: "POST",
    data: JSON.stringify({ "solution": data }),
    dataType: "json",
    headers: {
        Authorization: 'Basic XXX',
        'X-HTTP-Method-Override': 'PATCH',
        'Content-Type': 'application/json'
    },
    success: function (data) {
        alert("success");
    },
    error: function(xhr, ajaxOptions, thrownError) {
         alert(xhr.status);
      }
});
pee2pee
  • 3,619
  • 7
  • 52
  • 133
  • What is the JSON response? – Rahi Jan 17 '17 at 12:06
  • Check the other arguments to `error`, the second of which is actually `textStatus` according to [the documentation](http://api.jquery.com/jquery.ajax/). It might be a "timeout", "parseerror" or other built-in error. – Heretic Monkey Jan 17 '17 at 22:30

2 Answers2

2

The $.ajax function expects JSON data as response. If the response is not JSON, the error callback will be called. Please have a look at what you are sending out from server.

Ajay M
  • 139
  • 1
  • 6
0

Please test some things:

  1. Set type: "GET" instead of post. Look at this: GET OR POST

  2. Headers data are string (name/value), and maybe your data encoding is utf8 so set

    headers: {
    
       'Authorization': 'Basic XXX',  //high recommended
       'X-HTTP-Method-Override': 'PATCH',
       'Content-Type': "application/json; charset=utf-8"  //low
    },
    
  3. Test another word instead of data to avoid conflict:

    success: function (response)
    
Community
  • 1
  • 1
Farzin Kanzi
  • 3,380
  • 2
  • 21
  • 23
  • Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See [answer] for more information. Right now this looks more like a set of comments than an actual answer. – Heretic Monkey Jan 17 '17 at 22:27
  • Thanks dear @Mike McCaughan. I Edited my answer. – Farzin Kanzi Jan 17 '17 at 23:23