Neeraj Singh
Neeraj Singh

Reputation: 2146

How to access an API using jQuery

jQuery has cool methods like getJSON, get and load. However all of them in the end make AJAX call.

I am trying to access API www.eventsinindia.com/cities/mumbai/events.js?month=2009-05 .

This API call returns the data in JSON format.

I could not find any way to call this API from jQuery and to get the output data in JSON format. I keep getting Access to restricted URI denied" code: "1012 error because jQuery is trying to make an AJAX call. AJAX call from a standalone page to a server is forbidden.

Upvotes: 1

Views: 4422

Answers (3)

gregers
gregers

Reputation: 13040

If it's not a cross-domain request, you just need:

jQuery.getJSON("/cities/mumbai/events.js?month=2009-05", function(json) {
    alert(json[0]);
});

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

As @ceejayoz suggested JSONP technique must be used to access data on different domain. But in order for this to work the server side script must be JSONP enabled which means that it must accept a parameter that will define a client postback function name to prepend to the JSON data. If this is not the case you need to write a server script on the domain that is hosting your client script to serve as a bridge to the foreign domain.

Upvotes: 0

ceejayoz
ceejayoz

Reputation: 180004

As it's on a different domain, are you using a JSONP callback?

http://docs.jquery.com/Ajax/jQuery.getJSON

As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback. This callback parameter may vary depending on API, for instance Yahoo Pipes requires "_callback=?"

Upvotes: 2

Related Questions