6

I work with API Rest. I would like created a ressource with AJAX and JQuery. My ressource is created correctly but the error callback is called.

My code is :

$.ajax({
    url: "/api/skills.json",
    data: JSON.stringify(skill),
    method: "POST",
    contentType: "application/json",
    statusCode: {
        201: function (data) {
            console.log("201");
        }
    },
    success: function (data) {
        console.log("success");
    },
    error: function (data) {
        console.log("error");
    },
    complete: function (data) {
        console.log("complete");
    }
});

Result in "Network" from Firefox console :

HTTP/1.1 201 Created
Date: Thu, 27 Oct 2016 08:29:08 GMT
Server: Apache
X-Powered-By: PHP/7.0.8
Cache-Control: no-cache
Location: http://localhost/api/skills/pdak12ada64d
Allow: POST
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json

And result from Console :

"201"
"error"
"complete"

Why JQuery calls error's callback with 201 status ?

I tried with shortcut method $.postand same result, I don't use shortcut method because I use custom headers.

JohnnyC
  • 1,425
  • 1
  • 21
  • 38
  • 2
    On another question there's an answer suggesting that data type has to be `text` for `success` to be called when the response is empty - http://stackoverflow.com/questions/2233553/data-inserted-successful-but-jquery-still-returning-error – Adam Hopkinson Oct 27 '16 at 08:45

1 Answers1

2

As alluded to in my comment above, it seems that when jQuery.Ajax gets an empty response and tries to parse it as JSON, it throws an error which is then interpreted as an error with the response (rather than the parsing of it).

This means that you have two options - either send the request as text rather than JSON (which I wouldn't recommend) or handle responses using statusCode like you are doing in the question and remove the success and error callbacks.

Ref: https://stackoverflow.com/a/14988814/12280

Community
  • 1
  • 1
Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99