The FCC recently made available a small set of API calls to access FCC data. In particular, I'm interested in the Consumer Broadband Test API. I'm trying to access this API through jQuery but am failing. Please let me know if I'm doing something wrong with my code or if this seems to be a problem with FCC's API.
If you visit this API request in a browser, it returns a XML response just fine: http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999
So I've tried to load this data in jQuery using various methods:
var url = "http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999";
$.ajax({
type: "GET",
url: url,
success: function(data) {
console.log("ajax: " + data);
}
});
$.getJSON(url, function(data) {
console.log("getJSON: " + data);
});
$.get(url, function(data) {
console.log("get: " + data);
});
In the Firebug console, all three requests show a 200 (OK) status, but the response body is empty. Also, the resulting console.log messages are:
ajax:
getJSON: null
get:
Am I doing something wrong here?
To work around the Same Origin Policy, you'll need to use JSONP. It is supported by the API. Add callback=? to the URL string in your .getJSON() call:
If the URL includes the string
"callback=?" in the URL, the request
is treated as JSONP instead. See the
discussion of the jsonp data type in
$.ajax() for more details.
So, something like this:
var url = "http://data.fcc.gov/api/speedtest/find?...&callback=?";
$.getJSON(url, function(data) {
// do stuff
});
References: http://api.jquery.com/jQuery.getJSON/
You can't make cross-domain calls using AJAX. It doesn't work like that.
What you probably want to do is to have your AJAX query URL be a local script on your own server, then have that script run a request for the API url (using cURL or something).
Related
I am trying to retrieve a JSON from this URL
http://www.iheartquotes.com/api/v1/random?format=json
via jQuery. I know the solution is JSONP, but since I have no control over the response text of the service or to wrap it in my own callback function, my aim is to somehow retrieve the response of the above URL using client-end scripts.
I have tried almost all the methods suggested from several answers from StackOverflow.
These are the code blocks I have tried and the response's I've got.
1 . A direct call which returned the expected Access-Control-Allow-Origin error
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json",
function(data) {
alert(data);
});
Response:
XMLHttpRequest cannot load
=1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029.
Origin http://stackoverflow.com is not allowed by
Access-Control-Allow-Origin.
2 . The above code with the callback parameter added:
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?",
function(data) {
alert(data);
});
Response:
Uncaught SyntaxError: Unexpected token :
Please note that when I click on the error, it takes me to the expected JSON response.
{"json_class":"Fortune","tags":["simpsons_homer"],"quote":"Holy Moly! The bastard's rich!\n\n\t\t-- Homer Simpson\n\t\t Oh Brother, Where Art Thou?","link":"http://iheartquotes.com/fortune/show/5501","source":"simpsons_homer"}
This is also expected as there is no callback function defined in the response.
3 . Through jQuery's Ajax method
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://www.iheartquotes.com/api/v1/random?format=json",
success: function(data){
alert(data);
},
});
Response:
Uncaught SyntaxError: Unexpected token :
Adding the callback parameter to the above function doesn't change the response.
Any help or pointers from the experts to retrieve the JSON from the URL? I am testing this from the Chrome Dev Tools. I know I could call the service from the server-end code and then send it across to the client-end. But I want to see if this can be done through jQuery alone from the client-end.
EDIT:
Based on Kevin B's comment:
Got the expected output via YQL using jQuery's Ajax. But my question remains the same. Is there a native way to do it via jQuery as YQL is still a dependency?
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
q: "select * from json where url=\"http://www.iheartquotes.com/api/v1/random?format=json\"",
format: "json"
},
// work with the response
success: function( response ) {
console.log( response.query.results.json ); // server response
}
});
This gives the expected response.
This won't work in all browsers, but depending on which version of JQuery you're using try:
$.support.cors = true;
Obviously this also depends on the headers of the server response.
I was trying to get some information from another server using ajax post call as .
$.ajax({
type: 'POST',
url: testURL,
data: data,
//dataType: 'jsonp',
dataType: "script",
success: function (data) {
alert("Successfully posted (Test) : " + data);
},
error: function (ts) {
alert("Inside Error : " + ts.responseText);
}
});
Here testURL is the URL where i am posting the data (Cross domain requests are only possible if datatype is either jsonp or script), and it suppose to return text/html data back (what fiddler says will be the return type for the data).
I am not sure if i can use any proxy as pages are normal HTML pages.
Isn't there any way to get the [data] as text (as for now success expecting JASONP data and alert("Successfully posted (Test) : " + data); only showing data as undefined). I can't make any changes to API or whatever it is on the remote Server.
Thanks for the help in advance.
Regards
Without a proxy you cannot do it. If that is in a windows box, you can create a COM object to make the call to that server and from your JavaScript you call that COM.
UPDATE:
Well it seems you can with JSONP
jsonp with jquery
The response of my request is a java script code. When I put the url in browser, I can see the whole generated java script code on the page. Format of url passed to $.ajax is as below:
http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345
When I put the above URL I can see the request is successful. Now, I am using below Ajax request for this url using jQuery.
var finalUrl = "http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345";
var req = $.ajax({
type:"GET",
url:finalUrl,
type:"script",
data:"",
success: function(html){
alert('Requese sucessful.');
},
complete:function(jqXHR, textStatus) {
alert("request complete "+textStatus);
},
error: function(xhr, textStatus, errorThrown){
alert('request failed->'+textStatus);
}
});
Question 1:This gives the alert "request failed error'. Why this is so ?
Question 2:Is there any way to return success/failure code in above process?
In:
$.ajax({
type:"GET",
url:finalUrl,
type:"script",
(...)
You have two times the 'type' key in your object. So I think only the second one is taken ('script'). Obviously 'script' is not a valid HTTP method (as HEAD,GET,PUT,POST, etc). The keyword your were looking at for 'script' is maybe dataType which may be one of xml, json, jsonp, text, script, or html.
Do not forget to look at jsonp, it's usually a nice way to return a script content and to call it.
I am not sure why, but I can give your some tips how to debug or find out issues:
1) install fiddler to look at HTTP request.
2) type:"script", why the type is script? try to use "text/html".
3) use complete(jqXHR, textStatus) you can look at HTTP status. more info about $.ajax
var finalUrl=http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345;
is pretty invalid javascript. You probably meant passing the url as a string:
var finalUrl = 'http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345';
I'm trying to do a simple ajax GET that returns the html from google.com but with the following I keep hitting my onFailure. And when I hit status i get a 0, yet when I attempt to output the responseText I get nothing.
Anyone done a simple request like this in mootools 1.2.1?
function addSomeAction() {
el.onclick = function() {
var uri = "http://www.google.com";
var myRequest = new Request({
url: uri,
method: 'get',
onRequest: function(){
alert("loading...");
},
onSuccess: function(responseText){
alert("hi");
},
onFailure: function(responseFail){
alert("fail: " + responseFail.responseText);
}
});
myRequest.send();
}
}
Regardless of the framework used, you cannot do cross-domain AJAX requests. This is to prevent Cross-Site Request Forgery (CSRF) attacks and is a limitation imposed by the web browser.
Therefore, you can only fetch the HTML source of a page which on the same domain as the originating request.
There are specifications allowing for the asynchronous transfer of JSON data residing on another domain (JSONP), but they will not help you in this case.
I'm trying to use AJAX to send a query to Google Books and display the results on my website. I'm using JQuery to send the request and handling the response, like so:
var query = [formatted input from a form];
var URL = "http://books.google.com/books/feeds/volumes?q="+query+"&start-index=1&max-results=5";
$.ajax({
type: "GET",
url: URL,
dataType: "xml",
success: function(data, status){
alert(status);
}
});
Currently, I just have the script alerting "success" if a response is received. If I use my script to send that query to a local page for testing, this works just fine. But when I set the URL to the Google one listed above, as instructed on the Developer API page, I never see the alert. According to Firebug, I am receiving a response and a status of 200 ok as I should, but it's not getting to that "success" path. Does anyone know why?
Edit: I should add that if I follow the URL directly, to http://books.google.com etc. with some random q, it displays the feed XML with no problems, so the query is not the issue.
You can't make cross-domain requests using XMLHttpRequest under the standard browser security settings. One possible solution is to write a local proxy function (assuming you can create server-side code) that forwards the query to the external site, and then returns the response.
Edit: It looks like Google provides a JavaScript API as well. I would assume that they've crafted in such a way to avoid the cross-domain XHR issue.
http://code.google.com/apis/books/docs/js/devguide.html#execute
Edit: The JavaScript API for books was deprecated. While it's no longer practically useful, you can see the original referenced documentation text via the Wayback Machine archive: http://web.archive.org/web/20120414070427/http://code.google.com/apis/books/docs/js/devguide.html#execute
It's a cross-domain problem with ajax calls because browsers have a security model based on a domain policy.
if you don't wan to include the whole Google Books API, you can also use Google Ajax API with jsonp for cross-domain ajax calls.
Docs here:
http://code.google.com/apis/books/docs/js/jsondevguide.html#basic_query
jQuery example
var query = 'jquery';
var URL = 'https://ajax.googleapis.com/ajax/services/search/books?v=1.0&q=' + query;
$.ajax({
type: 'GET',
url: URL,
dataType: 'jsonp',
success: function( data, status ){
alert( data.responseData.results.length + ' results found!' );
},
error: function() {
alert( 'Something goes wrong!' );
}
});
Ciao!