I am trying to get information from an API. Basically I have a URL that returns a JSON data, and I will just need to use it.
var url = "http://212.18.63.135:9034/played?sid=1&type=json";
$.getJSON(url, function(data) {
console.log(data)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The above is my code, and it does not work.
This is an API that provides live data, so I am not sure if I can use ajax instead...
Any idea how to make it work?
UPDATE:
I updated the URL, and now it gives Access-Control-Allow-Origin error. I had a look at other question related to CORS and they all suggest to make configuration in the server side as much as I understood. But I am not looking into fixing the CORS error, I am just looking for a solution to access these JSON data.
So I hope it does not get duplicated as my point is different in this question.
You can do this way.
Adding callback=? to your URL turned your request to JSONP, so no CORS
More information about getJSON and JSONP.
If you interested how JSONP works you can read that article
var url = "http://212.18.63.135:9034/played?sid=1&type=json&callback=?";
$.getJSON(url, function(data) {
console.log(data)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you just want to access the data without doing any changes in the server.Try this chrome extension Allow-Control-Allow-Origin.
I just tested with the above, it's working fine.(browser specific though)
But this is not the recommended solution, you should set the configuration on server side.
Related
Could someone explain how I can access Wolfram's API data? I'm not worried about formatting for now--I would just like to learn the basics of interacting with the API.
The Wolfram website FAQ says this: "The Wolfram|Alpha API is designed to operate with interactive web technologies such as AJAX, Flash, and Silverlight."
And the documentation, which is located here: http://products.wolframalpha.com/api/documentation.html, says this: "A simple API call to retrieve output for the query "pi" would look like this:
http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
This query did not specify a desired output format, and the default is to retrieve the plaintext and image representations of each subpod. The image is returned as an <img> tag suitable for direct inclusion in a web page. Here is the output:"
I just have no idea how to put this together to actually access the Wolfram API data. Do I use AJAX or something else? What is the basic code for accessing the data?
I'm very new at this, so any help would be greatly appreciated. Thanks a lot!!
To use XMLHttpRequest their server must enable credentials by setting the Access-Control-Allow-Credentials response header to “true”
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
By AJAX I think they mean your server code should make the request.
In the next example they use Java Server Pages on their own domain to make the request:
https://reference.wolfram.com/webMathematica/tutorial/ApplicationsAJAX.html
Check other answers:
Wolfram API javascript cross origin sharing issue
If you use JQuery, a common javasSript framework, you can make an ajax request as follows
var requestData = function() {
$.ajax({
url: "http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX",
}).done(function(data) {
//data should contain the response from wolframalpha
});
I want to get some google search results in my website,I know I can get with curl,php but its limited daily for same ip adress. and I dont want to use google search api because its also has limit. So I think I can get with jquery ajax but I m a bit new on that,I am fed up with this problem.
here is my code, its will be always error because of jsonp format, but maybe still there is a way for catch html source code. I see source code comes to my browser but I cant take it like object.I tryed xhr.responseText etc but its gives also SyntaxError, still I cant get.
if you can suggest to me any other ways or if you have any idea with below code please share with me.
Thanks before now
$.ajax({
url:"http://www.google.com.tr/search?q=ercan",
dataType: 'jsonp',
success:function(json){
// I know its wont never succes, because google gives source in html format
alert("Success");
},
error:function(xhr){
//I want to get source code html here, but its giving always parse end syntax error I cant get it
console.log(xhr);
},
});
I am afraid that your only choices are to use the API or server side bridge script. You cannot do cross domain AJAX calls if the server doesn't support JSONP or CORS. There's also a commercial version of the API which allows you to increase the limit of requests you could send.
I have some problem with $.getJSON response in Chrome
The query is
$.getJSON("http://www.askgeo.com/api/428014/sf2t36ujv1tsf325t5734gstr4/timezone.json?callback=?&points=55.77184,37.623553",
function(json){
<some code>
}
);
if you click on this link you'll get an json text.
By when I run this query Chrome shows an error:
Resource interpreted as Script but transferred with MIME type application/json
SyntaxError: Unexpected token : timezone.json:1
Does it try to convert json response to JavaScript object? If it is so why it cann't do that? Is there any way of resolving this problem?
in Chrome debugger I found the file "timezone.json" with this content:
{"code":0,"message":"ok","data":[{"timeZone":"Europe/Moscow","currentOffsetMs":14400000,"latitude":55.77184,"longitude":37.623553}]}
The server you are requesting data from is not setup to return JSONP. therefore, you need to build some kind of proxy to get the data for you, or use YQL.
Edit:
If you were to use YQL, this is the url you would use:
http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22http%3A%2F%2Fwww.askgeo.com%2Fapi%2F428014%2Fsf2t36ujv1tsf325t5734gstr4%2Ftimezone.json%3Fpoints%3D55.77184%2C37.623553%22&format=json&diagnostics=true
and for information on how I generated that url, visit:
http://developer.yahoo.com/yql/console/#h=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22http%3A//www.askgeo.com/api/428014/sf2t36ujv1tsf325t5734gstr4/timezone.json%3Fpoints%3D55.77184%2C37.623553%22
You can find the url at the bottom.
Fiddle using YQL: http://jsfiddle.net/JGwU3/1/
there is however one quirk with using YQL. if the result only contains one result, it's contents is an object, however, if it is multiple, its contents will be an array. you can see the difference by console.logging the response.
In the API documentation it says, that you should provide the query paramaters in a separate JSON object as the second argument.
$.getJSON('http://www.askgeo.com/api/428014/sf2t36ujv1tsf325t5734gstr4/timezone.json', {'callback':'', 'points': '55.77184,37.623553'}, function(json) {
alert(json.data[0].timeZone);
});
Works fine when I tested it.
(This is totally ignoring JSONP)
EDIT
OK, my post was wrong, it is a JSONP issue. See this jQuery documentation page on how to retrieve the data from the URL:
http://api.jquery.com/jQuery.ajax/
Alright, so I'm building a web app that provides music information (i.e. info on artists, albums, songs, etc.) and for the info source I'm using the MusicBrainz API.
Now, I'm trying to load the data from an API call and process it, with jQuery. This is the code I'm using:
Code:
queryString="http://musicbrainz.org/ws/1/artist/?type=xml&name="+qry+"&limit=10";
$.ajax({url: queryString, dataType: ($.browser.msie) ? "text" : "xml", success: function(data){
alert("success");
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
};
...
With 'queryString' being the URL string for the request, and then I'd proceed to read the data out of the 'xml' object. Fairly simple.
However, this is where problems arise. The code works flawlessly when running locally on my computer, but does not work at all when I upload everything to my web server and try to run it there. I did some reading and have discovered that AJAX calls can't be made across different domains, due to security issues.
So I've read through numerous solutions, but almost all require either something with PHP (which I have absolutely NO knowledge of) or grabbing the data in JSON format (which apparently isn't subject to the same security restrictions). However, my main problem is that the MusicBrainz API does not return data in JSON format (in fact the only format it returns is XML).
So in any event, I was basically just wondering if anyone could give me some help or pointers on if and how I could grab that remote XML file using only JS/jQuery. Or, point me toward another method that could be accomplished by a complete PHP noob like myself.
Thanks for any help!
You require something on your server side to proxy your request to that other server. A URL that looks like:
/proxy?url=http%3A//musicbrainz.org/ws/1/artist/%3Ftype%3Dxml%26name%3Dexample%26limit%3D10
If PHP is available on your server, you can Google to find a generic PHP proxy script.
EDIT Here is an example of very simple PHP script that will retrieve a specified URL:
<?php readfile($_GET['url']) ?>
Note that you won't be able to POST any data to it, or specify a Content-Type. This is the most basic proxy required for very basic needs.
I understand that JSON is not an option right now but still, here is the explanation of why it can work for cross domain requests.
JSON being Javascript, it can be queried using the <script> tag instead of XMLHttpRequest. Since the <script> tag does not have the same restriction for cross domain request, it is possible to retrieve the JSON content this way.
This technique is called JSONP and is implemented in jQuery in the getJSON function.
If you don't want to setup your own proxy server, check out my response here: use jsonp to get xml cross domain
How do you get around this Ajax cross site scripting problem on FireFox 3?
If you're using jQuery it has a callback function to overcome this:
http://docs.jquery.com/Ajax/jQuery.ajax#options
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. Or,
if you set the dataType to "jsonp" a
callback will be automatically added
to your Ajax request.
Alternatively you could make your ajax request to a server-side script which does the cross-domain call for you, then passes the data back to your script
To update the answer (I guess, mostly for my benefit when I come looking for this answer later on), if are loading XML or something else, you can always ask the user if he will allow us to read from another site with this code:
try {
if (netscape.security.PrivilegeManager.enablePrivilege)
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
} catch (e) {
alert("Sorry, browser security settings won't let this program run.");
return;
}
(from the RESTful web services book) But, this only works in firefox, when the html file is loaded from local file. So, not that useful.
One more solution: if all you need is the headers, you can specify "HEAD" as the method and it won't trigger the security issue. For instance, if you just want to know if the web page exists.
var client = new XMLHttpRequest();
client.open("HEAD", my_url, false);
client.send(null);
if(client.readyState != 4 || client.status != 200) //if we failed
alert("can't open web page");
Some more details would be nice: which AJAX library are you using, what would you like to achive, how you do it.
For example it can be a cross-domain Ajax request, which is not allowed. In this case use JSON.
I came across this problem recently and it was while I as AJAX loading the local request, not cross site scripting problem. Also, Jimmy himself seems to have the same problem. This seems to be the FF security problem, this article describes the cause and the solution to access to restricted uri denied" code: "1012 problem.
Sorry, got that error using JQuery
$.ajax on FireFox 3. Tried jsonp
suggestion but I think that will only
work with something that will serve up
json. I'm trying to create a sample
local html file based mashup that will
pull data from Yahoo!Finance, but they
are serving .csv, so I think I'm SOL.
– Jimmy Chandra (Sep 9 at 17:20)
I hope you'll find it useful.