ajax 204 NoContent with no JSON in the response, will fire the ajax error handler.

ajax 204 NoContent with no JSON in the response, will fire the ajax error handler.

LordTonixLordTonix Posts: 5Questions: 2Answers: 0

After a ton of research, ajax blows up on a 204 if the body is empty, because it gets Content-Type: application/json so it attempts to parse the body for JSON and explodes. According to the jQuery: "your server design is flawed and broken." https://github.com/jquery/jquery/issues/2347 this is nonsensical.

Research says that if I do dataType: 'text' then jQuery will not try and parse the body, but DataTables does not seem to pass this to jQuery. For the record, I am using DataTables Editor REST interface.

               var editor = new $.fn.dataTable.Editor({
                    ajax: {
                        remove: {
                            type: 'DELETE',
                            url: 'http://localhost:53112/api/InventoryItems/_id_',
                            data: function (d) {
                                return JSON.stringify(d.data["0"]);
                            },
                            dataType: 'text' // <------ DOES NOT WORK
                        },
                    },
                    table: '#inventoryItems',
                    idSrc: 'Id',
                    fields: [
                        {
                            "label": "Name:",
                            "name": "Name"
                        },
                        {
                            "label": "Description:",
                            "name": "Description"
                        }
                    ]
                });

Answers

  • LordTonixLordTonix Posts: 5Questions: 2Answers: 0
    edited April 2018

    Solution:

    Override complete and use this:

    complete: function(xhr, textStatus) {
    
        // jQuery does not respect a 2xx with a JSON content type/data type and an empty body.
        if ((xhr.status === 200 || xhr.status === 204) && xhr.responseText === "") {
            xhr.responseJSON = {};
            xhr.responseText = "{}";
        }
    
     }
    
  • hnhegdehnhegde Posts: 68Questions: 17Answers: 0

    I am using jQuery 3.4.1. And I am seeing the same problem. Complete is not being overridden either. Any suggestions?

    Thanks,
    Harsha

  • hnhegdehnhegde Posts: 68Questions: 17Answers: 0

    I have it working now. Have noted down my solution in this thread.

    Regards,
    Harsha

This discussion has been closed.