I'd like to load a JSON feed from an external source using Javascript; what's the best method? I've been working a lot in PHP where it would be easy to do so with file_get_contents or cURL. Is there a related function or process in Javascript?
jQuery to get some JSON data might look like this:
$.getJSON("http://pathtodata.js", function(json){
alert(json.dot.notation);
});
A source is specified along with a callback function. Read up on jQuery JSON documentation:
http://api.jquery.com/jQuery.getJSON/
Javascript XMLHTTPRequest has same-domain origin policy so you will be restricted to only loading data from URLs from the same domain that your script was loaded from. JSONP is one way to get around this. Another way is to use a proxy script on your domain, which in turns performs its own HTTP calls for you. For more information on JSONP check out this article:
http://www.ibm.com/developerworks/library/wa-aj-jsonp1/
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 am trying to implement a simple request to Wikipedia's API using AJAX (XMLHttpRequest). If I type the url in the address bar of Firefox, I get a neat XML, no sweat there. Yet, calling the exact same url with:
// this is my XMLHttpRequest object
httpObjectMain.open("GET", "http://en.wikipedia.org/w/api.php?action=query&format=xml&prop=langlinks&lllimit=500&titles=kaas", true);
httpObjectMain.send(null);
returns an empty response. According to FireBug, I get a 200 OK response, but the content is just empty.
I suspect I might be missing something on the header of the GET http request.
Help! (and thanks!)
The Wikipedia API does support JSONP.
Your query string'll become something like this:
http://en.wikipedia.org/w/api.php?action=query&format=json&callback=test&prop=langlinks&lllimit=500&titles=kaas
But you'll have to build the jsonp handler (or you can use your favorite library to do it), switch to json output format from the xml you choose and create the callback function to parse the result and do the stuff you need on the page.
The browser will not allow you to send an XHR to another domain other than the one the page is on. This is for security purposes.
One way around this that I have seen is to setup a proxy on the domain the page is hosted on that will pass requests through to the actual api server. See http://ajaxpatterns.org/Cross-Domain_Proxy
I want to get a short string hosted on a server where I do not have access to the data as XML, JSON, etc. I am trying to use either .load or .ajax to do this. I want to be able to parse the data into a javascipt array. The entire contents of the remote page is text and I am happy to take all of it and remove what I do not need via a small javascript. I have tried:
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"http://url:8888/data", success:function(result){
$("div").html(result);
}});
});});
</script>
I have two questions.
1- why does this not work?
2- What would be the best way to store the string in a javascript var?
I am sure JQuery is working correctly.
The answer would be to long to post here (really). But look those up:
Same Origin Policy
Padded JSON
If you have no control over the remote site, you have lost - you will not get any data from it by Ajax (which is actually a feature, not a limitation of the technology). One way of circumventing the protection would be to build a proxy that just mirrors the remote service you need to reach and makes it available in the same domain that your main HTML came from.
My friend has a search engine that he wants to have a widget access that can be put on other web pages. If I send a request to the search engine, it returns an XML file. The request would look something like this:
http://www.site.com/page.php?keyword=this+is+a+sample&page=1&num_days=3&source_id=site2.com&source_name=site2&source_url=sampleurl.php
I understand how to access this by using Javascript. However, I know that you can't do a cross-domain request. I would have to have it load a new page at the search engines's site and not in the window at the the site they were located at....right? Any ideas or insight are greatly appreciated.
Here is a good explanation too:
What is JSONP all about?
EDIT:
jsonpString
Override the callback function name in
a jsonp request. This value will be
used instead of callback in the
callback=? part of the query string
in the url. So {jsonp:'onJsonPLoad'}
would result in 'onJsonPLoad=?' passed
to the server.
jsonpCallbackString
Specify the callback function name for
a jsonp request. This value will be
used instead of the random name
automatically generated by jQuery. It
is preferable to let jQuery generate a
unique name as it'll make it easier to
manage the requests and provide
callbacks and error handling. You may
want to specify the callback when you
want to enable better browser caching
of GET requests.
taken from:
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