I am new to Javascript. I need to parse XML using javascript or jQuery which is another server. I tried by using the below code. But when I executed it, it was not going to success method.
I was able to parse the XML which is in the same folder. Is it possible in javascript to access content from another server. I read the Same Origin Policy.
I was able to get the success message, but cant get the xml data
$.ajax({
type: 'GET',
url: 'http://10.47.5.69/myxml.xml',
dataType: "xml",
success: function(data){
alert('success');
$(data).find("Node").each(function() {
alert($(this).find("element").text());
});
},
error: err
});
function err(xhr, reason, ex)
{
alert('xhr.status: ' + xhr.status);
alert('ex "'+ex);
}
You cannot load something from another server due to cross-domain security checks.
However for javascript, there is a workaround: the JSONP technique: http://en.wikipedia.org/wiki/JSONP
It is used for JSON data but it can just as well be used for any string data. But it will only work if you have some degree of control (i.e. can install a script) on that server.
Another alternative is to proxy that URL on your own server. That might be easier.
Related
I wrote some php code that outputs some valid json, and sets the content-type header to application/json in my dev setup. However when I deploy this script to a embedded webserver it works fine except it's not capable of sending the content-type. It's not possible to run a other webserver.
Now I have the following code for Dynatable. Even though my dev and my embedded webserver, serve exactly the same file, and the only difference is the content-type. It works for my dev setup, however it doesn't work for my embedded setup.
I use the following code to load the json file to dynatable.
document.ready(
$.ajax({
url: 'phpApi.php',
success: function(data){
$('#myTable').dynatable({
dataset: {
records: data
}
});
}
}));
So can someone explain me why the content-type is so important for ajax? How can I tell my code manually its json?
Without the content-type the returned data is assumed to be plain text. There is nothing in your code to tell it otherwise.
One way to get json would be to specify the return type in the jquery code. Just add dataType: 'json' into the ajax configuration.
Or you could use eval() to transform the returned text to json.
document.ready(
$.ajax({
url: 'phpApi.php',
success: function(data){
$('#myTable').dynatable({
dataset: {
records: eval(data)
}
});
}
}));
Using JSON.stringify(eval(data)) might give you better results by making sure its json.
As pointed out below, JSON.parse(data) would probably be safer. (Eval is evil after all.)
So can someone explain me why the content-type is so important for ajax?
It's important so the client can identify what type of content the server returned, content-type: application/json tells jQUery to parse the data as an object. If no content type is returned, the client will assume the returned data is just plain text.
How can I tell my code manually its json?
Add dataType: "json" parameter to $.ajax()
document.ready(
$.ajax({
url: 'phpApi.php',
dataType: "json",
success: function(data){
$('#myTable').dynatable({
dataset: {
records: data
}
});
}
}));
I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.
I am calling the web service from other domain using Ajax call and I want to get returned response from server in my application by using following code I get response text in firebug but not in my JavaScript code. Control are not showing success and error response it goes out directly.
I want response in my success or error section but both not handling in this.
I am trying lot but not finding any solution please any one help me.
I am in a trouble. I hope somebody can help me for calling cross domain web service by using Ajax call. I am trying from 1 week but didn't find any solution till. I am getting response on browser but not getting it on my actual code.
My JavaScript code.
crossdomain.async_load_javascript(jquery_path, function () {
$(function () {
crossdomain.ajax({
type: "GET",
url: "http://192.168.15.188/Service/Service.svc/GetMachineInfo?serialNumber="+123,
success: function (txt) {
$('#responseget').html(txt);
alert("hii get");
}
});
crossdomain.ajax({
type: "POST",
url: "http://192.168.15.188/Server/Service.svc/GetEvents/",
// data: "origin=" + escape(origin),
success: function (txt) {
$('#responsepost').html(txt);
alert("hii post");
}
});
});
});
</script>
You can't simply ignore the Same Origin Policy.
There are only three solutions to fetch an answer from a web-service coming from another domain :
do it server-side (on your server)
let the browser think it comes from the same domain by using a proxy on your server
change the web service server, by making it JSONP or (much cleaner today) by adding CORS headers
i have wsdl file and i need get data from. How i can do this ? i'm trying do this with ajax
like this:
jq.ajax({
url: 'http://url.wsdl',
type: 'get',
success: function(data){
alert("OK " + data);
},
error: function (x, y, z) {
alert("ERROR");
}
});
what i do wrong ?
Any other way to get data from wsdl web service using javascript, jquery and etc. is?
I think what you are missing is a data: {}
I read that there was some sort of bug if you did not include that when using $.ajax
Oh, and most likely you are going to need dataType: "json" or whatever datatype the service is using.
Here is an example i am using against an online webservice:
jQuery.support.cors = true; //enables cross domain queries for Ajax
$('#jqueryBtn').click
(function ()
{
$.ajax
(
{
type: "GET",
url: "http://www.webservicemart.com//uszip.asmx/ValidateZip",
data: { 'ZipCode': '22553' },
dataType: 'html',
success: jqSuccess,
error: jqError
}
);
}
Hopefully you can use this example to fix your own code
http://forum.jquery.com/topic/jquery-ajax-to-call-a-wsdl-web-service
The following link should explain why you cannot use AJAX for cross domain queries:
http://www.w3schools.com/xmL/xml_parser.asp:
Access Across Domains
For security reasons, modern browsers do not allow access across
domains.
This means, that both the web page and the file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your web pages, the file you load must be located on your own server.
You can create a proxy web page in your web server to access to WSDL web service and return result to the AJAX request
$.ajax({
type: 'GET',
url: "string.txt",
cache: false,
success: function(str){
alert("Data is: "+ str);
}
});
In this example, string.txt is sent to the cache (\Temporary Internet Files)
How do I ensure that the file is not sent. I do not want copy to be sent.
Only a read from the server. Am I missing an option?
I set cache to false but that does not block it from being sent to client.
For example, ajax POST does not send a local copy.....
Here is some background info to what i am trying to do, but with jQuery.
I am curious as to why the standard ajax post seems to have the desired functionality I am looking for and am unable to do that with jQuery?
Thanks
Or set a no cache header server-side.