Ron
Ron

Reputation: 23526

AJAX - JQuery GET Callback not working but JSON file access ok

My code looks like this:

$.get('http://files.mysite.com/data.json', function(data) {
    console.log(data);
}, "jsonp");

When I take a look inside the Network menu from Firebug I can see a valid call to my JSON file and when I open it, it conains all the information.

But the Console remains silent. No sign of an AJAX call nor my logging of data.

My AJAX call is not on the same domain as my JSON file. Thats why I'm using jsonp

Any ideas??

Upvotes: 9

Views: 7203

Answers (3)

Gary Kenyon
Gary Kenyon

Reputation: 368

I'm not entirely sure what your problem is, if you get a result but the console stays quiet you could have issues with the JSON itself... try JSONLint to find issues.

Also I would recommend you don't use getJson etc.

$.ajax({
    url: http://files.mysite.com/data.json,
    dataType: 'jsonp',
    cache: false,

    beforeSend: function () {
        console.log("Loading");
    },

    error: function (jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
    },

    success: function (data) {
        console.log('Success');
        console.log(data);
    },

    complete: function () {
        console.log('Finished all tasks');
    }
});

This way you get some error handling and other nice little features, you could add a loading spinner via beforeSend, and remove it via complete :)

Edit: Replace the error function with the one below, that should give us a better idea of what the problem is :)

error: function (jqXHR, textStatus, errorThrown) {
  console.log(jqXHR);
  console.log(textStatus);
  console.log(errorThrown);
}

Upvotes: 17

Vivek S
Vivek S

Reputation: 5550

Its better to use $.getJSON instead of get if you know that the response will be json. The console should work now

$.getJSON('http://files.mysite.com/data.json', function(data) {
 console.log(data);
});

Upvotes: 0

Ted Xu
Ted Xu

Reputation: 1093

jsonp is not supported see here, only xml, json, script, html so use json instead if you dont have cross domain policy issue

$.get('http://files.mysite.com/data.json', function(data) {
    console.log(data);
}, "json");

Upvotes: 0

Related Questions