Get remote xml file by AJAX and parse it with jquery - ajax

I'm developing a HTML5 application for Blackberry OS 5+.
I'm using jQuery to download and XML file and show it using this function:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "http://xxx.com/yyy/mTop",
dataType: "xml",
success: function(xml) {
$(xml).find('item').each(function(){
var tipo = $(this).find('tipo').text();
var porcentaje = $(this).find('porcentaje').text();
$('<div class="items"></div>').html('<p>' + tipo + ' - ' + porcentaje + '</p>').appendTo('#page-wrap');
});
}
});
});
But I'm getting this error:
XMLHttpRequest cannot load http://xxx.com/yyy/mTop. Origin file:// is not allowed by Access-Control-Allow-Origin.
How can I parse a remote XML file?
Maybe I need to convert XML retrieved to a DOM object for use with jQuery.

That's because of Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites
you should use JSONP instead.

And the reason why you dont have a file location in your link ( url: "http ://xxx.com/yyy/mTop" ) is becouse the site "produces" an xml the moment you visit the folder, slowing down the website each time you reach it..
What you must do is:
go to http ://xxx.com/yyy/mTop on your browser
right click - view source code - copy to notepad - save as .xml
upload file to another folder
then change your code url to this url: "http ://xxx.com/yyy/mTop/yourdailyXMLcopy. xml
and keep updating the file daily..else you will kill the server querying each time any user uses your thing for a huge job...

Part of your problem is your file path is to a folder and not an XML file. Start there and see if you're problem still exists.

Related

ajax from same site as JS reference file?

I have a JS file running on my site, it works fine.
Now I want to put on another site with the full url of the script back to my site.
<script src="http://www-js.mydomains.com/some/path/file.js"></script>
now is it really still cross domain to an xml request on my server?
so in the file.js I have something like
dojo.xhrGet({url: '/some/path/file.xml', sync: true, handleAs: 'xml', error: function(result,args){alert(result.responseText+'-'+args.responseText)}, load: function(result){ ....
this just dies on other sites (great dojo response of undefined)... is there away around it
I think you should use "script" dojo/request/script instead of xhr.
require(["dojo/request/script", "dojo/dom", "dojo/dom-construct", "dojo/json", "dojo/on", "dojo/domReady!"],
function(script, dom, domConst, JSON, on){
on(dom.byId("startButton"), "click", function(){
domConst.place("<p>Requesting...</p>", "output");
script.get("helloworld.jsonp.js", {
jsonp: "callback"
}).then(function(data){
domConst.place("<p>response data: <code>" + JSON.stringify(data) + "</code></p>", "output");
});
});
});
http://dojotoolkit.org/reference-guide/1.9/dojo/request/script.html
now is it really still cross domain to an xml request on my server?
Yes. The origin is based on the URI of the HTML document hosting the script, not the URI the script was sourced from.
You should send the HTTP headers defined in the CORS specification to allow other sites to use your script (or their own scripts) to access content on your server.
Additionally, URIs accessed by JS are also relative to the document and not the script, so you will need to use an absolute or scheme relative URI instead of the server root relative URI you are presently using.

Absolute/relative address in ajax call in jquerymobile

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.

Screen scraping and proxies using Ruby

I know there are several screen scraping threads on here but none of the answers quite satisfied me.
I am trying to scrape the HTML from an external web page using javascript. I am using $.ajax and everything should work fine. Here is my code:
$.ajax({
url: "my.url/path",
dataType: 'text',
success: function(data) {
var myVar = $.get(url);
alert(myVar);
}
});
The only problem is that it is looking for the specified url within my web server. How do I use a proxy to get to an external web page?
Due to Cross Site Scripting restrictions, you're going to have to pass the desired URL to a page on your server that will query the URL in question from serverside, and then return the results to you. Take a look at the thread below and the incorporate that into your application and have it return the source when that page is hit by your AJAX function.
How to get the HTML source of a webpage in Ruby
Using a GET request is going to the be easiest way to transfer the URL of the page you want to fetch your server so you'll be able to call something like:
$.ajax("fetchPage.rb" + encodeURI(http://www.google.com))
Because you can't access the side in question directly from the server, you're going to have to pipe the serverside script through a proxy for the request to work, which really kind of depends on your setup. Taking a look at the Proxy class in Ruby:
http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html#method-c-Proxy

Ajax requests ignore virtual application sub-folder name in URL for ASP.NET MVC application

My application is located on the server under a separate virtual directory. To access my ASP.NET MVC application users have to go to:
http://server-dev/superApp
I have a problem with Ajax/Json server requests ignoring the "superApp" directory part. Whenever an Ajax request is made Fiddler shows 404 because instead of http://server-dev/superApp/User/GetUsersJson for example, http://server-dev/User/GetUsersJson is called (note the missing superApp name).
Example of an Ajax request:
function GetUsers(id) {
$.ajax({
url: "/User/GetUsersJson/",
data:{ id: id},
datatype: 'json',
type:'post',
success: function (result) {
////Do stuff with returned result
}
});
}
Registered route:
r.Match("User/GetUsersJson", "User", "GetUsersJson");
Where should I look and what can I change to make sure that my application virtual folder is ALWAYS included in all URL requests ?
p.s. Please note that all Javascript/Ajax logic is kept in separate .js files so no RAZOR syntax is available.
Did you try using the HTML helper method ?
url: "#Url.ACtion("GetUsersJson","User)"
EDIT : As per the comment
You may get the Path name using the HTML Helper method and Keep that in a Global variable and access that in the external javascript file
In the view
<script type="text/javascript>
var globalGetJSONPath='#Url.ACtion("GetUsersJson","User)';
</script>
And now you can use it in the external file like this
$.ajax({
url: globalGetJSONPath,
data:{ id: id},
//remaining items....
});
I solved this stuff by passing variable to js that contains hostname+vdir. Because of heavy js url generation.
In other cases Shyju's answer is best way to solve this.
No way to do it without some server-side code generation. Easiest thing would be defining global variable (sorry) holding you application root and initializing it somewhere in master page.
Javascript generation of route urls always was one of the messiest parts of asp.net mvc.

jquery $.ajax() in safari and chrome doesn't work

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"));

Resources