I'm using jQuery (1.7.0) to make a json/ajax call to Spotify. The following code works fine in Chrome and Firefox, but causes an error (Error: Access is denied.) in IE.
$.ajax({
url: 'http://ws.spotify.com/lookup/1/.json',
type: 'GET',
dataType: 'json',
cache: true,
data: {
uri: "someartist",
extras: "album"
},
success: successfn,
error:function(xhr, status, errorThrown) {
alert("networking error: "+errorThrown+'\n'+status+'\n'+xhr.statusText);
}
});
The success function is called in Chrome and FF, but the error function is called in IE with the above message. I have set cors to true: jQuery.support.cors = true;.
It works on Chrome and FF both locally and on my server, it works in IE locally but not on the server. Changing cache: false causes problems at the spotify end - doesn't line additional parameters, so I get a "bad request" error.
Grateful for any pointers.
Thanks
Abo
You are relying on the spotify url to give a Access-Control-Allow-Origin:* in their header to allow cross domain requests from all domains. Internet explorer however doesn't support this, so it gives access denied.
access-control-allow-origin explained. (TLDR: Servers may allow cross domain ajax in their headers)
If you need this to work in IE, you could use spotify's JSONP API if they have one or make the AJAX request in flash, which works in all browsers and passes the requests response data to your javascript.
The above answer about using jsonp is correct; I want to add:
Don't set
jquery.support.cors = true;
I'm not sure why so many questions begin by stating they took that step. This property is meant to be read to find out if the browser supports CORS. You should only override it if you know differently, and in my experience it's accurate for all major browsers. Setting it to true doesn't enable the browser to use CORS, it just denies you the info that CORS is going to fail.
http://api.jquery.com/jQuery.support/
can you give an example of returned data?
at a /guess/, it either has something to do with the filename ".json", or the JSON returned has something weird about it.
I'm surprised this works on Chrome or Firefox. You shouldn't be able to run cross-domain JSON requests.
If Spotify API supports it, you should use JSONP in order to access resources from other domains.
Also see: No response from jQuery ajax call
I don't see this working in FF. You can't make cross-domain Ajax calls. So I'm not sure what's going on when you say that it works in FF. But I just tried the following in FF and I got the error. So all you can do is make the call on the server side and then include the results in your page.
http://jsfiddle.net/2XWGn/
Related
Please excuse my bad english, I'm french ;)
SO, I've to make an Ajax call you this kind of url :
http://maps.googleapis.com/maps/api/geocode/json?latlng=45.85941212790755,0&sensor=true
With this code :
$.ajax({ url:'http://maps.googleapis.com/maps/api/geocode/json?latlng='+pos.coords.latitude+','+pos.coords.longitude+'&sensor=true',
success: function(results){
// ...
}
});
But it never succeeds for IE8 (It's ok for chrome and FF, IE9&10).
Have you got an idea ?
EDIT
My bad, in IE8 you cannot request a geocode from the client side any longer because google has removed JSONP support from their geocoder.
You can do one of two things
Use your own server as a proxy (I do this).
This basically means that you make a request to a script on your own server that uses cURL (or similar) to make a request to the google geocoder and then return the results back to you.
If you're using the google maps api, you have the option of using it's built-in geocoder (https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple)
OLD REPLY
It's a cross domain call in IE8 - you'll get a No Transport error (or if you add jQuery.support.cors = true you'll still get an Access is Denied error.
Best solutions is to use JSONP. jQuery makes using JSONP trivial.
Check out this jQuery Docs page and scroll down to their example using JSONP with the Flickr API.
Hi i have the following code
var dataString = "email=jdoe#example.com&fname=John&lname=Doe&phone=7851233&vid=726&size=2&date=2013-05-28%202:15%20PM&request=Testing%20A%20Message";
$.ajax({
type: "GET",
timeout: 5000,
url: "http://www.livepicly.com/app/api.php?method=add_reservation",
data: dataString,
success: function(data, textStatus) {
alert(data.result);
},
error: function(xhr, textStatus, errorThrown){
alert("ERROR");
}
});
return false;
Where basically i would like to submit a piece of string to this URL:
http://www.livepicly.com/app/api.php?method=add_reservation
The formatted string (as displayed by firebug) is like this:
http://www.livepicly.com/app/api.php?method=add_reservation&email=jdoe#example.com&fname=John&lname=Doe&phone=7851233&vid=726&size=2&date=2013-05-28%202:15%20PM&request=Testing%20A%20Message
When the string is executed via browser (straight copy-pasting) it works perfectly. It displayed the corresponding message.
However, when i execute the code, it always returns error. Does anyone know why this happen?
Cheers,
The API in question is not RESTful.
Anyway, your problem is a combination of factors. What it definitely is NOT is the API actually throwing an error, as all errors are returned as 200 status codes. (Not RESTful Point #1). So, even if livepicly returned an error, it'd still count as success on jQuery handlers.
In no particular order:
The API is not throwing Access-Control-Allow-Origin headers. It does not support JSONP either. (This can be seen by querying http://www.livepicly.com/app/api.php?method=add_reservation&callback=test ). This will completely prevent jQuery from loading any data of performing any queries to the API due to cross-domain restrictions
That's the only thing that is failing! This is also completely preventing jQuery usage. You'll need to make a choice to go around this one, which may or may not include:
Proxying the API locally. This is trivial if your webserver is running thanks to Apache or nginx. For Apache, use ProxyPass and ReverseProxyPass directives using mod_proxy, or use a rewrite rule with the [P,L,QSA] set of flags. On nginx, use the proxy_pass directives. If you have access to neither, proxy it using curl through PHP.
Giving the developers of the API a slap in order for them to simply add Access-Control-Allow-Origin: * to the headers, which will make your call work
Giving the developers of the API a slap in order for them to support JSONP
Overall, just point them to https://en.wikipedia.org/wiki/Representational_state_transfer and give them a slap for me. Please?
I am having a rather frustrating problem with the jquery post function that probably stems from not understanding how it works correctly.
I have a function that should post some form information to a php script that I wrote and that script then runs curl requests against an API to get around the cross-domain policy of javascript. It seems to work fine as long as it submits to "http" but when I send it to "https" the form never gets submitted.
I ran wireshark on my computer and it showed no traffic towards the destination ip until I made the url use http. I have basic auth on the server so I am passing the user and password through the url, but tested without that there and got the same results.
Here is the not working code:
$j.post("https://<api user>:<password>#<ip>:444/ProxyScript.php",
$j("#spoke_ticket").serialize(),
function(msg) {
log_status(msg);
fade_status();
$j(':input','#createtheticket')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
});
Here is the working function:
$j.post("http://<other ip>/ProxyScript.php",
$j("#spoke_ticket").serialize(),
function(msg) {
log_status(msg);
fade_status();
$j(':input','#createtheticket')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
});
Any ideas as to why the traffic is not being sent?
Let me know if I left out some key information or anything.
Thanks for the help
If you are doing the AJAX post from a http page to a https URL then the Cross-Domain policy kicks in because the protocol is also part of the origin specification, as it is described here. The browser will refuse to make the AJAX call, so that's why you're not seeing any traffic.
A solution is discussed here:
Ajax using https on an http page
So your best bet is the Access-Control-Allow-Origin header which should be supported on most modern browsers now.
So make your server add the following header to the responses:
Access-Control-Allow-Origin: https://www.mysite.com
If for some reason you cannot enforce this, then the only choice left would be JSONP.
Why not use a proxy to get over the cross-domain issue? It sounds more easy. An simple example is when i want to retrieve the danish administration national geo-data for counties,road names and so on (lucky for me, their data is in json or XML optional)
simplified proxy.php
<?
header('Content-type: application/json');
$url=$_GET['url'];
$html=file_get_contents($url);
echo $html;
?>
in ajax, get the lat/longs for a county borderline
var url= "proxy.php?url=https://geo.oiorest.dk/"+type+"/"+nr+"/graense.json";
$.ajax({
url: url,
dataType: 'json',
success: function (data) {
...
});
notice the https - the url could be, real example, https://geo.oiorest.dk/kommuner/0810/graense.json
I have a https site. I'm running LifeRay on Tomcat. I'm using the following URL:
http://gdata.youtube.com/feeds/api/videos/ID?v=2&alt=jsonc
and
jQuery.ajax({
url: URL,
dataType: 'jsonp',
async: false,
success: function (obj) {
processData(obj);
}
});
to get the data and then processing it. It works on all the browsers. The only problem is that I get a security warning in IE8.
Question 1: Is there any way to get the JSON data securely and processing the data without IE throwing any warning messages?
Question 2: How and where can I set this: Access-Control-Allow-Origin: http://youtube.com, so that maybe IE won't throw any warning messages?
Try using
https://gdata.youtube.com/feeds/api/videos/ID?v=2&alt=jsonc
Since you are in https, IE wants all resources accessible within that domain to be secured. I feel previously you were using http:// in the request URL of youtube. Change it https, it may solve the security warning issue.
If a secure page loads any nonsecure resource, its going to throw the warning. The only way to get around it is to load everything from https.
Here you are trying to load a non secured resource (http://gdata.youtube....) in the secured website.
HTH
I want use $.ajax to read some infomation from xml file,here is my js code :
$.ajax({
type: "get",
url: "Database/App_all.xml",
dataType: "xml",
timeout: 2000,
beforeSend: function () {
},
success: function (xml) {
$(xml).find("app[id='id-1']").appendTo($("#contain"));
},
error: function () {
alert("ajax failed!");
}
});
However, the code only work great in firefox and opera.
It doesn't work in chrome(7.0.517.24 ) and safari(5.0.1),failed without any alert,not even the alert("ajax failed").
Is there any bug in $.ajax in chrome and safari?so how to solve the problem?
thank you very much:)
You should use chrome's or safari's built-in developer tools (ctrl+shift+i) to track JS errors and track actual AJAX requests.
Is your code wrapped in document.ready? Is there any erros in javascript console? Also try to output something after success callback line.
Another cause for this could be incorrect mime-type for your XML file returned by server. It should be [Content-type: text/xml]. You can check that in chrome's or safari's built-in developer tools - just look for headers tab when xml resource is selected. If it 's actual problem, you may need to tweak web-server configuration (main config or .htaccess for apache) to return correct mime-type.
First thank you gajendra.bang and Māris Kiseļovs give me your advices,I have konw what's wrong with my code,after I get a bad resault ,I trying to know what the $.ajax get from xml exactly,so I use firebug check the div#contain I found that:
<div id="contain">
<auther>cocept</auther>
</div>
yes,I think the <auther></auther> must the problem,I don't even konw the $.ajax would get the tagname as well
so I rewrite it :
success: function (xml) {
$("#contain").html($(xml).find("app[id='id-1']").find("auther").text());
}
then the div$contain is:
<div id="contain">
cocept
</div>
so ,the chrome and safari could show again!
I suppose you have problem with reading of the local file per ajax. Ajax can be used to read a file from the same web server, but there are some security restriction if you read it not per HTTP.
In firefox and opera you can read local files (with url like file:///C:/Program%20Files/My/Database/App_all.xml) per ajax without any problem.
In Internet Explorer you should use dataType: 'text' and then convert the text to XML (read more here).
To be able to read local files in Chrome you have to restart chrome with another parameters:
chrome.exe --allow-file-access-from-files
(Be sure that all other instances of chorme closed before starting Chrome.exe in the way).
This is a problem for local files... You should try uploading them on a web server and check from there
$(xml).find("app[id='id-1']").appendTo($("#contain"));
what is xml basically returning, an element with "#" like "#mydiv" or class like ".mydiv"
I think you are trying to access an element and if you are not returning it with "#", try
$("#"+xml).find("app[id='id-1']").appendTo($("#contain"));