McFarlane
McFarlane

Reputation: 1877

jQuery dataFilter response undefined

I am fetching data from an external api via jsonp with jQuery.ajax().

this is my ajax setup:

var ajax_options = {
    dataType: 'jsonp',
    jsonp: 'callback',
    url: url,
    data: parameters,
    success: function (response) {
        console.log(response); // works, prints the correct data
    },
    dataFilter: function (response, type) {
        console.log(response); // prints undefined
        console.log(type); //prints "jsonp"
    }
};
$.ajax(ajax_options);

I want to use the dataFilter function to preprocess my response for error handling. But the response argument of this function is always undefined. In the success function however, I get the correct response data.

Do you know what might be the problem?

Upvotes: 3

Views: 3936

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50798

I can verify that this issue is a pain in the arse. What needs to be done is to use $.ajaxSetup({}); along with the converters:

$.ajaxSetup

http://api.jquery.com/jQuery.ajaxSetup/

Then, you'll need to use Converters to handle your dataType, dataFilters, callbacks, and parsing.

jQuery.Extensions - Converters

http://api.jquery.com/extending-ajax/#Converters

While you don't have to use Converters via $.ajaxSetup -

$.ajax({ converters: 'params go here' });

Because of the scenario you're facing, all data that is passed as your jsonp needs to have this converter applied to it. This should provide you with a more realistic control based on your expected result type and needs.

Upvotes: 1

Related Questions