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"));
Related
I'm trying to request a google sheet from the client in javascript, using jquery ajax.
The following code works in Chrome but fails in Firefox.
Question : how can I get it to work in Firefox?
If it's a server configuration issue then does this mean it's impossible to link to google drive documents from a firefox client?
Here is the code:
var url = 'http://docs.google.com/spreadsheets/export?id=1-on_GfmvaEcOk7HcWfKb8B6KFRv166RkLN2YmDEtDn4&exportFormat=csv';
$.ajax({
url : url,
type : 'GET',
dataType : 'text',
success : function(res, status){
console.log('status : ' + status);
console.log(res);
},
error : function(res, status, error){
console.log('status : ' + status);
console.log(res);
console.log(error);
}
});
In Chrome I get a 307 response then a 200 with the desired data.
In Firefox I get a only a 200 response but with the error message something like "Access-Control-Allow-Origin header missing, Same Origin Policy does not allow to fetch this resource".
The problem is that docs.google.com does not set CORS headers on redirects. And Chrome is not following the specification by not enforcing that and therefore has a security bug of sorts.
docs.google.com is in Chrome's HSTS preload list. The request to http://docs.google.com is transparently rewritten to https://docs.google.com, so no redirect happens.
I assume this will resolve itself if Firefox pulls an updated copy of the HSTS preload list. As Anne notes, simply changing the link to https directly will solve your use case.
I found a workaround by configuring Google Drive slightly differently, and using JSONP :
1) In Google Drive, Publish on the web the document & set sharing options to Public
2) Export your data in JSON format with a JSON type link, it will look like : "http://spreadsheets.google.com/feeds/list/YOUR_FILE_ID/od6/public/values?alt=json&callback=myCallback". You need to append &callback=myCallback to use JSONP. You can use jQuery to make your JSONP call.
3) To use the data, you need to define the callback function specified in the url , in this case "myCallback"
I've mentioned a similar procedure in a different answer but I think it can be useful to mention it here as well since it directly relates to the problem I was facing.
#EnricoFerreguti you should replace YOUR_FILE_ID with your file ID. Example : https://spreadsheets.google.com/feeds/list/1-on_GfmvaEcOk7HcWfKb8B6KFRv166RkLN2YmDEtDn4/od6/public/values?alt=json from the http://misterfresh.github.io/react-drive-cms/ website .
The following code works fine in iPads and iPhone (4,5) in Safari and Chrome. In contrast, the ajax call won't work (runs straight to the onError function) in Android devices and desktop browsers.
When I exchange the absolute URL for a relative one, the success/failure outcomes are reversed in these two groups.
How do I get around this problem (I'm running jquerymobile 1.3.0 beta)? Thanks/Bruce
$(document).ready(function() {
$("#submit").click(function(){
var formData = $("#loginf").serialize();
$.ajax({
type: "POST",
url: "http://mydomain.org/m2/scripts/site/bpg_process.asp?id=lg",
cache: false,
data: formData,
dataType: 'json',
success: onSuccess,
error: onError
});
return false;
});
});
Do you know that cross-domain Ajax calls are not allowed ?
Your problem may be linked to the URL from which you're making the request, and not to the browser you're testing in.
Read this for more details : http://en.wikipedia.org/wiki/Same_origin_policy
The important thing here for you is that the policy excludes different subdomains.
Ex. if you're sending a request from http://www.mydomain.org to http://mydomain.org it will fail, and vice versa.
What i do in your case usually is use the complete URL "/m2/scripts/site/bpg_process.asp?id=lg" without the protocol and host but with the starting "/" so it can be referenced from anywhere in the URL tree.
What is the "relative URL" that you're using and that "doesn't work"?
Like darma has mentioned. "cross-domain Ajax calls are not allowed".
Use absolute "local" pathing instead.
a slash '/' at the beginning of a link referees to the document root.
if you need to refer to an external domain, use ajax to call a local .asp document that calls the external page for you and returns the data you want in json.
Im not sure what this is in asp but in php, curl works.
As the title says, I'm trying to access (POST) using jQuery AJAX call to a web url, http://host:port/... or http://localhost:8080/... from a local HTML file, c:\home.html. I can't get it to work.
I did Google and also saw several questions here but I can't get it to work. I need some help here. Here is what I've tried so far.
dataType: jsonp
crossDomain: true
Setting the header in my response:
response.setHeader("Access-Control-Allow-Origin", "*");
None of the three browsers are working - IE, FF or Chrome. The request is never reaching the server. Here are some of the errors I'm seeing.
No Transport (IE) if not jsonp is used.
NS_BINDING_ABORTED / Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED) in FF
This is my code. I would appreciate any help. I'm using jquery-1.8.2.min.js.
var http_host = "http://localhost:8080";
function su (pc, p) {
var suUrl = http_host + "/ps/api/v2/authorize.json";
$.ajax({
type: 'POST',
url: suUrl,
data: {
phone_cell: pc,
password: p,
},
dataType: "json",
crossDomain: true,
success: osu,
error: oe
});
return false;
}
function osu (d) {
console.log(d);
}
function oe(xhr, ts, et) {
alert("ServerError: " + et);
}
An example would be a perfect pointer.
I suppose my code got messed up w/ all the different solutions that I was trying. I was finally able to get it to work w/ setting the header (solution that was recommended and worked for others). All that I had to do to get it to work is add the following to my REST service response.
response.setHeader("Access-Control-Allow-Origin", "*");
Update:
I thought I figured this out but I've not. There is more it than just setting the header. Anyways, in my specific situation. I was trying to run my app (html, js) off of the hard drive specifically on chrome and trying to access web services available on the cloud.
Here is how I finally solved the problem. I started the chrome w/ the following parameters.
--disable-web-security -–allow-file-access-from-files
Like I mentioned earlier, this app is really a desktop application that will be run as part of the chromium embedded framework.
Thanks every one for your input.
You can't make a cross-domain request from a local file because it's not on a domain. You need to host C:\home.html on a local webserver instance in order for it to work.
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/
I am making an ajax request using JQuery that looks like this:
var data = createXMLdata();
$.ajax({
url: 'http://localhost:8080/foo/bar',
type: "PUT",
data: data,
processData: false,
contentType: "application/text",
error: function(xhr, status, error) {
alert("Error: " + status);
},
success: function() {
alert("Success!");
}
});
When the code executes, I get the success alert, but the service is never executed on the server!
Here's some more data:
If I make the same request using a separate REST client, the service is executed correctly
If I shut down the server (nothing is running) so that hitting that URL gives me a 404, I still get a success message.
I have tried replacing the data with "foo". This works from the REST client, but gives the same result from the code.
Any ideas are greatly appreciated!
The documentation about .ajax()'s type attribute says:
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
So probably your browser does not support PUT and the data is sent via POST instead (and therefore not recognized by your service).
Use Firebug or similar to find out which method is used.
One idea to make it working:
Send the data using POST but add an additional field e.g. __http_method=PUT. On the server side, your service has to recognize this and perform the PUT functionality.
This might be not the nicest solution but it is also used by other frameworks I have encountered (e.g. symfony for PHP).
PUT isn't supported by all browsers
Nick Craver made a comment on my question:
Is the page you're running this in served from port 8080?
It turns out this led to me solving the problem. When both the app and the service were hosted on the same server (and port), the problem went away.
This post suggests that if I comment answers the question, and the commenter does not re-post as an answer, I am to post my own answer and accept it. Nick, if you return to post this as an answer, I will accept it over my own.