简体   繁体   中英

AJAX success failure callback not working

I have a table and I have a delete button. Basically what I want to do is when I click on the delete button, it will send a DELETE request to our server and update on the db. If it's successful, it will remove that row from the table.

Config.js

var SiteConfigProxy = function () {
"use strict";

var getSiteConfig = Config.apiUrl + "/configs/site/{siteId}";
var addDevice = Config.apiUrl + "/configs/device/{deviceId}";

var delete1 = function (url, data, done, fail){
    $.ajax({
        type: "DELETE",
        url: url,
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (typeof (done) === 'function') done(data);
        },
        failure: function (data) {
            if (typeof (fail) === 'function') fail(data);
        }
    });
};

return {
    deleteDeviceConfig: function (deviceId, data, done, fail){
        delete1(addDevice.replace("{deviceId}", deviceId), data, done, fail);
    }
};
} ();

siteconfig.js

        configTable.on("click", ".delete", function (event) {
        event.preventDefault();
        if (confirm("Are you sure to delete this row?")) {
            var tableRow = $(this).parents("tr")[0];
            var data = {
                siteId: tableData.fnGetData(tableRow)[1],
                hostname: tableData.fnGetData(tableRow)[2]
            };

            SiteConfigProxy.deleteDeviceConfig(tableData.fnGetData(tableRow)[0], data,
                function(data){
                    tableData.fnDeleteRow(tableRow);
                    console.log("delete succeeded");
                },
                function(data){
                    console.log("delete failed");
                }
            );
        }
    });

Right now every time when I click on the button, it won't remove that row and the console won't log that statement. I am just wondering why the success and failure callback isn't working.

Thanks a lot

Since your server script is not returning a valid JSON response, it should invoke the failure callback (because attempting to parse the response as JSON fails). But the correct name of that option is error: , not failure: . So change it to:

    error: function (data) {
        if (typeof (fail) === 'function') fail(data);
    }

If the server isn't supposed to send back a JSON response, leave out the dataType: option, and it won't try to parse it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM