pee2pee
pee2pee

Reputation: 3792

jQuery ajax - error runs even though it ran successfully

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

Upvotes: 0

Views: 162

Answers (2)

Farzin Kanzi
Farzin Kanzi

Reputation: 3435

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)
    

Upvotes: 0

Ajay M
Ajay M

Reputation: 139

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.

Upvotes: 2

Related Questions