I am trying to get a value from this URL (returns pure XML):
http://demo.piwik.org/?module=API&method=VisitsSummary.getUniqueVisitors&idSite=7&period=day&date=today&format=xml&token_auth=anonymous
And I want to store this value in this element on a separate site:
<div id="result" style="color:red"></div>
Every javascript or jquery attempt I try results in some "access-control-origin" error, which I understand to a point but I can't do anything about the remote server. I need a quick front-end solution.
Note: There is another format I can return the data in - JSON. But I have had similar issues above in trying to get that data as well.
Because you are trying to make cross domain request and because server only allow jsonp for cross domain request, then use jsonp. For example:
$.ajax({
url: 'http://demo.piwik.org/?module=API&method=VisitsSummary.getUniqueVisitors&idSite=7&period=day&date=today&format=json&token_auth=anonymous',
dataType: 'jsonp'
}).done(function(data){
$('#result').html(data.value);
});
-jsFiddle-
Related
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.
I have a situation where I need to get data from an HTML file existing in another server. It will contain simply plain text content and nothing else. I don't have access to change anything there nor I can get any structured html. What I have is only text content stored in an HTML which is hosted in http://host1.demoserver.com.
Now, from my application which is hosted in http://host2.demoserver.com, I need to get the content through an ajax call. Problem is without implementing CORS. So, upto to my knowledge level I have an option JSONP. But, when I make ajax call with JSONP, I can see the response in Firebug, but it starts throwing javascript exception. There reason that comes into my mind(may be I am not correct) is that, since the content comes as callback parameter it contains undefined variables.
HTML file: copyright-info.html
This is a simple copyright info which needs to be rendered.
And, if we make a call with ajax call:
$.ajax({
url: "http://host1.server.com/static/copyright-info.html?callback=?",
method: "GET",
dataType: "jsonp",
jsonpCallback: "callback",
callback: function(result) {
//code to excute after success
}
});
Then, response would be like:
callback(This is a simple copyright info which needs to be rendered.)
And, as parameter is not in double quotes its not recognizing it and throwing exception.
2nd, this whole thing was working without JSONP, when it was in localhost. And, I guess, http://host1.demoserver.com will be same localhost as it is for http://host2.demoserver.com. But, when it is deployed in server its failing.
Can anyone suggest what's wrong here? Or, any other way for implementing this.
Thanks in advance.
Ok, after an whole day trying to get this to work I just don't seem to know what's the deal with this, so here it goes:
I have a WebService hosted locally by now (http://localhost:15021/Service1.svc/[whatever_method]) and an HTML Page on a different file.
FYI, both WebService and HTML Page will get hosted on different servers.
I'm trying to get some info off the WebService to the HTML Page by the onload=load() method in the HTML Page.
My JavaScript code is:
function load() {
alert("Loading...");
$.ajax({
url: 'http://localhost:15021/Service1.svc/getAllNoticias',
type:'GET',
dataType: 'jsonp',
jsonp: 'loadNews_callBack'
});
}
function loadNews_callBack(result){
alert(result.data);
}
Additionally, the JSONP is loaded on the Page with an OK (200) status (As you can see here) which should (I guess) call the callback function, but it isn't.
What can I do to get around this? I already change the request parameters 500 times (e.g., added "?callback=? to the url, with or without jsonp attribute, etc...)
Any help would be great,
Thanks in Advance
Check the actual response text to verify that the response is correctly being wrapped by the callback function. It is possible that your service is not setup correctly to handle JSONP so it simply responding with JSON. It will still come back as 200, but fail to execute.
loadNews_callBack([json...])
vs
[json...]
See this question as reference on how to go about updating your service:
ASP.net MVC returning JSONP
I'm pretty new to programming, and recently have been playing with Twitter API. From statuses/sample method, how would you read the content of following URL using Javascript?
https://stream.twitter.com/1/statuses/sample.json
Edit: perhaps I shall explain my intention. I'm trying to read the Twitter sample data, read the hashtags every 30 seconds, and then sort them ascendingly every 30 seconds the top 10 hashtags.
The problem is, I'm not even sure how to read the Twitter data in the first place..
Not looking for solutions, but definitely could use some ideas.. especially for getting started.
You should be able to utilize JSONP which is a special type of response back from the server.
It basically takes the response, wraps it in an anonymous function callback, and returns it to the client inside of a script tag thereby calling it when the response gets back to the browser.
$.ajax({
type: 'post',
dataType: 'jsonp',
url: 'http://twitter.com/status/user_timeline/msdn.json?count=10&callback=?',
success: function (data) {
console.log(data);
}
});
Inspecting the request url in Chrome's debugger you'll see the request...
https://twitter.com/status/user_timeline/msdn.json?count=10&callback=jQuery1706531336647458375_1335842234009&_=1335842234045
And the response back is...
jQuery1706531336647458375_1335842234009( /* data */ );
Then jQuery wraps the data in the script tag and appends it to the body.
Notice how the callback in the request matches the function call in the response.
Hope that helps!
You can't. Read up on cross site scripting.
Basically you're going to need to proxy your request through the hosting server.
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