In trying to use the stackoverflow api with ajax and jquery and I just can't get it to work. I know I have to use jsonp as the datatype and I keep reading different ways of doing the jsonp request but I still can't get it to work.

I know that I am doing something really dumb because I ran into the same issues when trying to use the Twitter api but I can't for the life of me remember what I did to get it to work.

Update

So I took a loog @genesis's working demo and tried it a few time and different ways but no luck. Then I notice my jQuery version and switched it to the one he was using and it magically worked.

I change the most recent version
http://code.jquery.com/jquery-1.6.2.min.js
to
http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js

hmm no idea why it works, possibly a bug but who knows maybe something else changed.

If anyone knows why it would be awesome if you could explain. Also I realize that jQuery adds the callback automatically but I could not get it working like that. What could I do to get this working, I guess you would say a "more proper" way?

4 Answers
4

You can add jsonp:'jsonp', to the ajax() call. The stackoverflow API documentation states that it needs the jsonp query paramater and the jQuery property to configure the query string parameter passed is called jsonp. Without it, the default is to add callback=? to the end of the URL.

Update 2: Based on comments, here is another version, this time wrapped in an object. Note that you cannot use jsonpCallback: 'api.onJsonp', because that is only defined inside the jQuery anonymous function. The simplest way to keep the encapsulation is to create a global function and just pass control back to the api counterpart.

Beautiful! Only one little problem. I got it to work with a global function. I get success and the onJsonp method is called. Once I change onJsonp to api.onJsonp the callback gets called but the ajax error handler fires.
–
locrizakJul 23 '11 at 14:19

as a baidaid solution to this I put api.onJsonp.apply(api, arguments); in the global onJsonp function but I would really rather call api.onJsonp as the request callback and get a successful response.
–
locrizakJul 23 '11 at 14:47

@locrizak what you want is impossible I think due to the api.onJsonp only existing in the jQuery anonymous closure. I have updated my answer with an improved example that should do what you want.
–
andybJul 23 '11 at 21:06

Yeah thats what I thought just checking if I was missing anything that I should be doing to get it to work. Thanks for your help
–
locrizakJul 24 '11 at 18:15

I have tried api.onJsonp... api being the closure name as well as a global onJsonp method. You cannot pass the function name without the quotes, it needs to be a string because it is added onto the request, not called right away.
–
locrizakJul 22 '11 at 23:51