Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.getJSON returning undefined to success callback in IE9 and below

We've encountered an odd problem with a $.getJSON call which only seems to affect older versions of IE. Code is as follows:

var success = function (response) {
     // do stuff
}

$.getJSON(url, success);

Under Chrome, Firefox, IE10, this code works just fine - getJSON hits the URL (which is valid, and is not cross domain), returns 200 OK and returns the data, which is passed through to the success function as you'd expect.

However under IE9 and below, the success callback is invoked but the response parameter passed through is undefined. By capturing the network traffic in IE Dev Tools I can see the call hitting the URL, returning 200 OK and returning valid JSON in the response body. So why is this coming out as undefined when it hits the success callback?

I've tried using the $.ajax call instead with appropriate parameters, and I see the same behaviour. Code below:

$.ajax({
    dataType: "json",
    url: url,
    success: success
};

We're using jQuery 1.7.2 (one of the libraries we've got on the page is broken under the newer version of jQuery, hence the old version).

EDIT: Just tried updating the page to use jQuery 1.10.1, doesn't fix the issue.

EDIT 2: I've confirmed that the JSON data being returned is valid via jsonlint.com so that isn't the issue either.

like image 968
Henry Wilson Avatar asked Nov 01 '22 12:11

Henry Wilson


1 Answers

If it is caching the result then set the cache to false before the request:

$.ajaxSetup({ cache: false });

If it is caching the result then use ajax instead of getJSON:

$.ajax({
    url: 'data.json',
    cache: false,
    dataType: 'json',
    success: function(data) {
        console.log('success', data);
    },
    error: function (request, status, error) {
        console.log('error', error);
    }
});

If the mime type is wrong then specify the dataType:

$.getJSON('data.json', 'json', function(data) {
    console.log('getJSON', data);
});

If the mime type is wrong then specify the dataType on the server:

header('Content-type: application/json');

If it's a variable conflict then rename your callback variable:

var success = function (newname) {
    console.log('success', newname);
}
$.getJSON(url, success);

If it's cross origin request then you can force jQuery to use it with:

$.support.cors = true;
like image 197
Kim T Avatar answered Nov 13 '22 22:11

Kim T