Nathan Ridley
Nathan Ridley

Reputation: 34406

jQuery dataFilter somehow results in null data sent to ajax success callback

I have defined an ajax dataFilter for my jQuery calls that return JSON data to ensure that .Net-encoded dates are automatically converted to JavaScript dates on return:

$.ajaxSetup({
    dataFilter: function(data, type) {
        var rx = /"\\\/Date\(([0-9]+)\)\\\/"/g;
        if(type == 'json' && typeof(data) == 'string' && rx.test(data)) {
            var obj = JSON && JSON.parse ? JSON.parse(data) : eval(data);
            replaceMicrosoftJSONDates(obj);
            return obj;
        }
        return data;
    }
});

The replaceMicrosoftJSONDates function works fine; it recursively iterates through the object and replaces strings matching the appropriate date format string with actual JavaScript dates, but here it is for testing purposes:

function replaceMicrosoftJSONDates(obj) {
    for(var p in obj)
        switch(typeof(obj[p])) {
            case 'string':
                var match = /^\/Date\(([0-9]+)\)\/$/.exec(obj[p]);
                if(match) obj[p] = new Date(parseInt(match[1]));
                break;
            case 'object':
                replaceMicrosoftJSONDates(obj[p]);
                break;
        }
}

The problem is with the dataFilter function. If I return the modified JSON object, null is sent as the data parameter to the ajax success callback:

$.ajax({
    type: 'GET',
    cache: false,
    url: __appPath + 'path/to/my/page',
    success: function(data) {
        console.log(data); // displays null
    }
});

As far as I can tell, the jQuery private function involved in this process is ajaxConvert, which you can see at https://github.com/jquery/jquery/blob/master/src/ajax.js#L897-979

Keep in mind the following:

If I return a string from the dataFilter function, jQuery does its job correctly and sends me a parsed JSON object. If I return a pre-parsed JavaScript object, jQuery sends null to my success callback. I am using jQuery 1.5.2 in this case and this filter used to work in other applications and older versions of jQuery. Now all of a sudden it doesn't seem to work anymore.

SOLUTION

Here: http://forum.jquery.com/topic/datafilter-function-and-json-string-result-problems

Upvotes: 4

Views: 6000

Answers (2)

sakhunzai
sakhunzai

Reputation: 14500

Just a quick comment from my experience :

wherever you put dataFilter method for remote validation just ensure that it returns stringyfied boolean values sth like this:

     return   $.toJSON(true)  
  or 
     return  $.toJSON(false)

I lost couple of hours to find this :)

Upvotes: 1

tpeczek
tpeczek

Reputation: 24125

Rick Strahl had problem similiar to this recently (this seems to be specific for jQuery 1.5.2). As I don't wan't to copy his work, here is his solution which should easly guide you to solve your problem: http://codepaste.net/i89xhc

Upvotes: 3

Related Questions