beldaz
beldaz

Reputation: 4471

jQuery ajax handling of 204 No Content

I am writing an jQuery ajax call to a RESTful server, for which the response to a valid PUT request is an HTTP 204 No Content. The response has a Content Type header of application/text but there is no content body. Because of this, it appears that the ajax call threats this as an error, and so the error function is called instead of done.

Is there a way to override this behaviour, and execute done for a 204 response regardless of the content body?

Upvotes: 1

Views: 2108

Answers (2)

Prateekro
Prateekro

Reputation: 566

Best way would be to make a call for statusCode in ajax. And make a runner code in specific statusCode.

new Promise((resolve, reject) => {
    var settings = {
            "URL": "<your link>",
            "method": "POST",
            "timeout": 0,
            "headers": {
            "Content-Type": "application/json"
            },
        "data": JSON.stringify({
            "email": email,
            "user_name": user_name,
        }),
        "statusCode": {
            200: function (data) {
                console.log("Request completed 200");
                resolve(data || {statusCode: 200});
            }, 
            201: function (data) {
                console.log("Request completed 201");
                resolve(data || {statusCode: 201});
            },
            204: function (data) {
                console.log("Request completed 204");
                resolve(data || { statusCode: 204});
            }
        }
    };

    $.ajax(settings)
});

Upvotes: 1

beldaz
beldaz

Reputation: 4471

I finally managed to fix the problem by adding a filter to the ajax request settings

dataFilter: function(data,type) {
    return data || "{}"
}

This ensures that JSON.parse never receives empty content when it is called within ajax on the response content.

Upvotes: 3

Related Questions