5

I had a JSONP URL, that was pulling data and just switched to a local JSON file and now I am getting errors. I don't understand why it is not working with a local JSON file?

<script type="text/javascript">
    $.ajax({
        type : 'GET',
        dataType : 'json',
        url: '/json/topics.json',
        success : function(data) {
            console.log(data); 
            var topics = [];
            $.each(data.results, function(index, obj){
                topics.push({
                    username: obj.TopicName,
                    mentions: obj.LastHourCount,
                    totalcount: obj.TotalCount,
                    daycount: obj.Last24HoursCount
                }); 
            });
            $('#leader').tmpl(topics).appendTo('#top3');
        } 
    });
</script>

In the console it is saying AJAX is a anonymous function for some reason? Any suggestions?

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Xtian
  • 3,535
  • 11
  • 55
  • 91

1 Answers1

3

$.ajax is asynchronous and it looks like you are trying to change the DOM on page load, add

async: false,

to your $.ajax parameters. Note that it may slow down page load.

Example:

 $.ajax({
    type : 'GET',
    dataType : 'json',
    async: false,
    // rest of your code

See this post if you are using local files, not through webserver, and getting a Origin null is not allowed by Access-Control-Allow-Origin error:

Error: "Origin null is not allowed by Access-Control-Allow-Origin" when loading an XML file with JQuery's ajax method

Community
  • 1
  • 1
jk.
  • 14,365
  • 4
  • 43
  • 58
  • after adding that i get this error: XMLHttpRequest cannot load file:///json/topics.json?_=1327938971630. Origin null is not allowed by Access-Control-Allow-Origin. – Xtian Jan 30 '12 at 15:50
  • @Xtian check the path to your `topics.json` file. Seems like the issue is there now. – jk. Jan 30 '12 at 15:51
  • @Xtian This post might help: http://stackoverflow.com/questions/5396527/error-origin-null-is-not-allowed-by-access-control-allow-origin-when-loading – jk. Jan 30 '12 at 15:56
  • I put it up on a server to make sure this wasn't the issue. The console is outputting the data, but then I get the error: Uncaught TypeError: Cannot read property 'length' of undefined – Xtian Jan 30 '12 at 16:14
  • @Xtian Sounds like your question was answered and now you have an issue with the data returned. I can't see the data so it's very hard to troubleshoot this issue. You said it was jsonp and now it's json so take a look at the data and make sure it is in the correct format for how you are attempting to read it. – jk. Jan 30 '12 at 16:23
  • 1
    +1: 1 yr after this was posted, i find it to be a life saver! :) – mihirj Mar 10 '13 at 12:46