Toby Mellor Toby Mellor - 3 months ago 12
Ajax Question

JQuery AJAX - Filter before .done()

My application has a lot of AJAX calls, each of them return a JSON response. Instead of validating the data in each of the the .done() calls, I'm trying compact the code.

What we have so far

$.ajax({
url: 'test',
type: 'GET',
data: {
_token: token
},
dataFilter: function(jsonResponse) {
return isValidJson(jsonResponse);
}
}).done(function(jsonResponse) {
// do things
});

isValidJson(jsonResponse) {
try {
var parsedJson = $.parseJSON(jsonResponse);

if (parsedJson.error == 1) {
notificationController.handleNotification(parsedJson.message, 'error');

return false;
}
} catch (err) {
notificationController.handleNotification('A server-side error occured. Try refreshing if the problem persists.', 'error');

return false;
}

return jsonResponse; // Have to return the original data not true
}


The expected behavior is that if dataFilter returns false, it will trigger .fail(), if it returns true then it will continue to .done(). Instead, it just continues to .done() with the result of isValidJson().

Is there also a way to make .fail() do something standard like send a notification to the user without having to put it under every AJAX call?

Answer

Easiest way is to create a shorthand for $.ajax, by extending it.

Extending the AJAX call

jQuery.extend({
    myAjax: function(params){
        // Here we can modify the parameters and override them e.g. making 'error:' do something different
        // If we want to add a default 'error:' callback
        params.error = function() {
            console.log('its failed');
        };

        // or you can specify data parse here
        if (params.success && typeof params.success == 'function') {
            var successCallback = params.success;
            var ourCallback = function(responseJson) {
                if (isValidJson(responseJson)) { // Validate the data
                    console.log('The json is valid');
                    successCallback(responseJson); // Continue to function
                } else {
                    console.log('The json is not valid');
                }
            }

            params.success = ourCallback;
        }

        return $.ajax(params);
    }
});

Now everytime you want to make an AJAX call in your application, you DO NOT use $.ajax({}). Instead, you use $.myAjax({});

Example

$.myAjax({
    url: 'domain.com',
    type: 'GET',
    success: function(data) {
       // Do what you'd do normally, the data here is definitely JSON.
    },
    error: function(data) {}
});

And this special function will handle all errors same way, no need to write those validators every time.

Comments