How can I use public APIs in a Javascript application? For example I want to make a call to the Zillow API using JQuery AJAX.
When issuing the request in JQuery AJAX (shown below) I get the following error:
XMLHttpRequest cannot load "MY HTTP REQUEST URL". Origin "MY WEB DOMAIN" is not allowed by Access-Control-Allow-Origin.
var requesturl = "http://www.zillow.com/webservice/GetRegionChildren.htm?zws-id="+zwsid+"&state="+state+"&city="+city+"&childtype=neighborhood";
Code:
var jqxhr = $.ajax({
url: requesturl
})
.done(function(data) {
console.log(data);
});
I've also tried adding crossDomain, dataType and headers params (shown below), but they haven't helped.
var jqxhr = $.ajax({
url: requesturl,
crossDomain: true,
dataType: 'xml',
headers: { 'Access-Control-Allow-Origin': '*' },
beforeSend: setHeader
})
.done(function(data) {
console.log(data);
});
Most popular public API's support JSONP request. Refer API documentation for details.
Cross ajax domain request is restricted. So you will be needing to make JSONP request. Don't worry JQuery will handle most of it.
Sounds like you need to register your url with Zillow, maybe contact them / hunt around on their doc pages. Also jquery has a get method which makes ajax requests even simpler. There's also getJSON if that is the return format.
Related
Is it possible to make xhr request between domains www.site.mySiteName.com and api.mySiteName.com using JavaScript?
I need to get data from my API in real-time but I don't know how to do it.
Making it possible (Opening your API to your webpage):
You can do ajax requests between domains, however, the host has to allow your origin.
You need to append the header to the response (this needs to be done on the API):
Access-Control-Allow-Origin: *
Or something like:
Access-Control-Allow-Origin: site.mySiteName.com
The API will technically respond to any origin unless you specify otherwise regardless of the header; however, the browser will say the request failed if your origin is now allowed.
Additionally, you should be aware that depending on the request your API will have to support preflight "OPTIONS" requests
See:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
How does Access-Control-Allow-Origin header work?
To actually make the request in javascript:
You can use jQueries "ajax" to make the request: http://api.jquery.com/jquery.ajax/
Simple get request:
$.ajax({
method: "get",
url: "test.html",
}).done(function(data) {
console.log('got data:' + data);
});
Simple post request:
$.ajax({
method: "post",
url: "test.html",
data: {somekey: 'somevalue'}
}).done(function(data) {
console.log('got data:' + data);
});
Format response as JSON:
$.ajax({
method: "get",
url: "test.html",
dataType: "json"
}).done(function(data) {
console.log('got data:' + data);
});
Note(edit): You could do this in native javascript; on the other hand, using jQuery or AngularJS(a full application framework..) is simpler and adds other useful tools.
This question already has answers here:
Unexpected token colon JSON after jQuery.ajax#get
(2 answers)
Closed 7 years ago.
I am trying to get data with Ajax.
Data is json. I use jquery and angular.
But result is undefined or error.
Here is my jquery code:
$(document).ready(function() {
var url = "http://market.dota2.net/history/json/";
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
});
In Angular i am usin jsonp method. Whats wrong ?
By the way, in pure Java i can get data from this url...
Whats wrong?
You're trying to call an endpoint that provides JSON as though it provided JSONP. That won't work; they are different (though related) formats.
Example JSON:
{"foo":"bar"}
Example JSONP:
callback({"foo":"bar"})
Note the difference: JSONP is actually a JavaScript function call, wrapped around the JSON.
If the API supports JSONP, call an endpoint that supports it.
If not, you can't query it directly unless the provider supports Cross-Origin Resource Sharing and shares with your origin, because of the Same Origin Policy that applies to ajax calls.
By the way, in pure Java i can get data from this url...
Because the Java code is not running in a context that is controlled by the SOP, and so can get the data from that endpoint (as JSON) and use it. This is also the same reason that just posting that URL into a browser address bar lets us see the data. But ajax calls are governed by tighter rules.
If you expect json, dont use jsonp but json.
$(document).ready(function() {
var url = "http://market.dota2.net/history/json/";
$.ajax({
type: 'GET',
url: url,
async: true, /* it fails with false */
contentType: "application/json",
dataType: 'json',/* <== here */
success: function(data) {
console.log(data);
}
});
});
Are you using jsonp consciously ? Do you know what it is ? If not, use json. Or get informed about JSonP: https://en.wikipedia.org/wiki/JSONP
I tried on Safari:works.
On Chrome & FFox: does not work + Erreur "Cross Domain Origin"
XMLHttpRequest cannot load http://market.dota2.net/history/json/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
That means you cannot get JSon with your client/machine from the API server. So you should indeed use JSonP, but... you miss the callback or something in the API documentation.
I am trying to use the lastFM API. I have started with a very basic template where all i wanted to do was connect to the LastFM API and authenticate myself. I have a button on my HTML page -
<button id="auth">AUTHENTICATE</button>
Here's the jQuery function to handle the click event -
$(document).ready(function() {
$("#auth").click(function() {
console.log("authenticate called");
var myUrl = "http://www.last.fm/api/auth/?api_key=32*************8a*****2";
/*$.get(url,function(data) {
alert("data");
});*/
$.ajax({
// The 'type' property sets the HTTP method.
// A value of 'PUT' or 'DELETE' will trigger a preflight request.
type: 'GET',
// The URL to make the request to.
url: myUrl,
xhrFields: {
withCredentials: false
},
crossdomain : true,
headers: {
// Set any custom headers here.
},
success: function(data) {
// Here's where you handle a successful response.
},
error: function(data) {
console.log(data);
});
});
});
I am running this on my localhost. As you can see from the AJAX request, it supports CORS. I can also see CORS header attributes being added to my request headers. But the server needs to respond with the CORS headers too like Access-Control-Allow-Origin. But the response does not contain any such headers.
But lastFM API supports CORS, so shouldn't it be sending these attributes in the response headers? Also, now how can I make use of CORS to authenticate my application?
P.S - I know I can use JSONP, but I want to know if there is any way I can handle this using CORS?
Thanks to #potatopeelings, I got the answer. What we need was not to call the authentication url, but to redirect it to a seperate page which will ask me to authorize the application to use the lastFM account. I also provided a callback URL which will redirect to my application after I have given the authorization.
So my final URL is like -
myURL = "http://www.last.fm/api/auth/?api_key=XXX&cb=http://localhost:63342"
And I removed my AJAX call to do the following -
window.location.replace(myUrl);
I'm using a jquery ajax call to a recurly API endpoint, but I get cross-origin errors. From my understanding, this is because Recurly only returns results as XML... when I use JSONP to get around cross-origin errors, I get an error because it receives the XML data but expects JSONP. Pretty obvious. But I'm trying to understand how exactly can one use this API at all via AJAX calls. I've been successfully able to access the API with PHP, but unfortunately, for this project, I can't use any client-side code.
Even if I find some sort of middle-code solution to get the XML and convert it to JSON for my side to accept, I need to utilize the API for POST requests (creating accounts, subscriptions, etc.) so I would like to understand how to utilize the API properly.
Here is an example of my code:
$.ajax({
url: "http://[DOMAIN].recurly.com/v2/accounts",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + window.btoa("[API KEY]"));
},
crossDomain: true,
type: "GET",
accepts: "application/xml",
dataType: "application/xml; charset=utf-8",
success: function (data) {
console.log("SUCCESS:", data);
},
error: function(e){
console.log("ERROR:", e);
}});
Anyone with Recurly API experience have any tips/advice?
From https://docs.recurly.com/api/recurlyjs/jsonp_endpoints
$.ajax({
dataType: 'jsonp',
url: 'https://{subdomain}.recurly.com/jsonp/{subdomain}/plans/{plan_code}',
data: {
currency: 'USD',
},
success: function (data) {
// do stuff
},
}
You should not use the V2 API from the browser. Doing so risks exposing your private API key. If someone has your API key they can make calls charging customers, modifying subscriptions, causing all sorts of problems.
Look at the JSONP endpoints that Byaxy linked to.
I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
});
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation?callback=run');
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);