9

We've written a RESTful server API. For whatever reason, we made the decision that for DELETEs, we would like to return a 204 (No Content) status code, with an empty response. I'm trying to call this from jQuery, passing in a success handler and setting the verb to DELETE:

jQuery.ajax({
    type:'DELETE',
    url: url,
    success: callback,
});

The server returns a 204, but the success handler is never called. Is there a way I can configure jQuery to allow 204s to fire the success handler?

5 Answers 5

11

204 should be treated as success. What version of jQuery are you using? I did a couple of tests and all 200 range status codes went to the success handler. The source for jQuery 1.4.2 confirms this:

// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( xhr ) {
    try {
        // IE error sometimes returns 1223 when 
        // it should be 204 so treat it as success, see #1450
        return !xhr.status && location.protocol === "file:" ||
            // Opera returns 0 when status is 304
            ( xhr.status >= 200 && xhr.status < 300 ) ||
            xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
    } catch(e) {}

    return false;
},
Sign up to request clarification or add additional context in comments.

1 Comment

Okay, now I'm confused. I'm trying this again, and it appears to be working. It looks like I must have been doing something else incorrectly. Thanks!
9
+50

I had a simliar issue because my script was also sending the "Content-Type" header as "application/json". While the request succeeded, it couldn't JSON.parse an empty string.

Comments

3
jQuery.ajax({
    ...
    error: function(xhr, errorText) {
        if(xhr.status==204) successCallback(null, errorText, xhr);
        ...
    },
    ...
});

ugly...but might help

1 Comment

Thanks sje397, that makes sense. You think it's the only way?
3

It's technically a problem on your server
Like Paul said, an an empty 204 response with a server content-type of json is treated by jQuery as an error.

You can get around it in jQuery by manually overriding dataType to 'text'.

$.ajax({
    url: url,
    dataType:'text',
    success:(data){
       //I will now fire on 204 status with empty content
       //I have beaten the machine.
    }
});

Comments

2

This is alternative way to callback on success... I think that will work for you.

$.ajax({
    url: url,
    dataType:'text',
    statusCode: {
                204: function (data) {
                   logic here
                }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.