0

Using jquery's $.ajax function, I'm not able to parse the results. For example, I used it like this

$.ajax({

    url : "http://api.twitter.com/1/users/show.json?screen_name=techcrunch",
    dataType : "json",
    success : function(data)
    {
        // parse the JSON here
    },
    error : function()
    {
        alert("Failure!");
    },

});

This doesn't work. Do I need a callback function?

Jonathon Bolster
  • 15,811
  • 3
  • 43
  • 46
  • Please define "doesn't work". What result do you get and what result do you expect to get? – Matt Asbury Jan 04 '11 at 16:38
  • sorry, should've been more clear. If I just execute the URL in the browser, http://api.twitter.com/1/users/show.json?screen_name=techcrunch, I get back the JSON data. But with the above code, I don't get any data back - Firebug shows nothing in the response. I'm not sure what I'm doing wrong. –  Jan 04 '11 at 16:42

2 Answers2

1

As metnioned, this is due to the Same Origin Policy. To get around this, you should set your datatype to jsonp.

$.ajax({

    url : "http://api.twitter.com/1/users/show.json?screen_name=techcrunch",
    dataType : "jsonp",
    success : function(data)
    {
        console.log(data);
    },
    error : function()
    {
        alert("Failure!");
    },

});

Example: http://jsfiddle.net/jonathon/bpnbj/

Jonathon Bolster
  • 15,811
  • 3
  • 43
  • 46
  • Awesome, that worked. I didn't know what JSONP is, thank you. –  Jan 04 '11 at 17:06
  • this wont handle the error situation when an error occurs. jquery cannot handle jsonp error situation , it simply hides it !! see the below fiddle -- http://jsfiddle.net/zrvPy – Tito Apr 16 '12 at 18:39
0

You can't make an ajax call to an external url due to Same Origin Policy. You can see more info in Call external url through $.ajax in wordpres theme thread.

Community
  • 1
  • 1
jny
  • 8,007
  • 3
  • 37
  • 56