Cross domain issue XMLHttp - javascript

I face the common cross domain issue with xmlhttp.
I am trying to access WSDL web service using the SOAP protocol. I am not using php and so I can not use the
header('Access-Control-Allow-Origin: *');
I also can't use JSONP as the response I get is not in JSON format but in XML format.
Is there any other way that I can resolve this issue.
Here is my code snippet.
var user1="user_name";
var pass1="******";
var url="http://ideone.com/api/1/service.wsdl";
var soap_msg="<?xml version='1.0' encoding='UTF-8' standalone='no'?>"+
"<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'"+
"xmlns:tns='http://ideone.com:80/api/1/service' xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/'"+
"xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/'"+
"xmlns:soap-enc='http://schemas.xmlsoap.org/soap/encoding/' "+
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' >"+
"<SOAP-ENV:Body><mns:getLanguages xmlns:mns='http://ideone.com:80/api/1/service' SOAP- ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>"+
"<user xsi:type='xsd:string'>"+user1 +"</user><pass xsi:type='xsd:string'>"+pass1+"</pass>"+
"</mns:getLanguages></SOAP-ENV:Body></SOAP-ENV:Envelope>";
var oXmlHttp= new XMLHttpRequest();
oXmlHttp.open("POST",url,true);
oXmlHttp.setRequestHeader("Content-Type", "text/xml");
oXmlHttp.setRequestHeader("SOAPAction", "http://ideone.com/api/1/service#getLanguages");
oXmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
oXmlHttp.send(soap_msg);
var res=oXmlHttp.responseXML;
Thanks in advance.

Here's a link from YUI that you will probably find useful.
http://developer.yahoo.com/yql/guide/yql-jsonp-x.html
They've written a callback which is essentially an envelope that allows for XML to be returned.

Just for the record, Allow Access headers should be set on the server side, that is, on ideone.com which you don't control. At that point, all you can do is along the lines of easyXDM.

Related

Get data out of JSON array from external URL

I am relatively new to JSON. I have read the tutorial and trying to implement it but no luck.
Basically I have an external URL that gives JSON data/feed. The data is in the form of array. Now I am trying to write a JavaScript Program (on my local) that would get the data out of this URL and would put in my html.
Here is the function. It includes the external link also.
But I am not getting any result. Just empty.
Am I missing something or what I am doing wrong?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Index Page</title>
</head>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://mpatrizio-001-site5.smarterasp.net/categoryList.php?D=B7ACEF70-4901-41C8-930F-D4D681D82DAA";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].CategoryID + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
UPDATE:
After being pointed in the right direction by you guys (thank you very much for that), I have found that the request is being blocked by server due to some CORS error. I am studying it.
Please review the following image of the error I got in the console.
From it, can you specifically point out the solution?
Append --disable-web-security (at path C;...\chrome.exe) in chrome's exe properties preceded by a space.
More Elegant Solution:
Other solution will be on server side. Which is to create crossdomain.xml and clientaccesspolicy.xml file on server. It's structure is like:
crossdomain.xml:
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
</cross-domain-policy>
clientaccesspolicy.xml:
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="SOAPAction">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
Some of the tutorials are:
http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000469.html
http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html
Its specification is:
http://www.adobe.com/devnet-docs/acrobatetk/tools/AppSec/CrossDomain_PolicyFile_Specification.pdf
Other tutorials:
https://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspx
What you are trying to do, Is a cross domain request. A cross domain request is also called a JSONP request amongst many more others and has two restrictions:
The first is that it restricts you only to "GET" requests, meaning you cannot issue a "POST" request to the cross domain server.
The second is that you are very limited by the server, meaning that if the server won't allow, you cannot get any data.
I would suggest you to read more about cross domain request before trying to go through this.
You are probably trying to execute an XMLHttpRequest to a domain that is different than your page is on, the browser will block this request. To allow the request you have to use CORS.
You can open the developer tools in Chrome (F12) and check for any error messages related to
"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '[domainname]' is therefore not allowed access."
Thank to Muhammad Imran, Barr J and Luuk Moret, I am finally able to solve my problem.
It was the Cross domain request that's why it was not allowing me to get data.
So what I did,
I checked using test-cors.org the server to which I was sending request to see if CORS is configured or not. And the server was configured.
Then I installed this plugin for chrome, "Allow-Control-Allow-Origin: *" This plugin allows to you request any site with ajax from any source. Adds to response 'Allow-Control-Allow-Origin: *' header and Whola!. That solved my problem.
I hope this would help someone else.

Define Javascript Variable With Contents of URL

I have found a geocoder website that will give me some data that I need as a variable in my javascript code: http://geocoder.us/service/csv/geocode?zip=95472. the website returns only the content: 38.393314, -122.83666, Sebastopol, CA, 95472. I need pull this information from the website and put it into a string.
abc = "38.393314, -122.83666, Sebastopol, CA, 95472"
How can I accomplish this?
You can use AJAX:
var req = new XMLHttpRequest(); //Create an AJAX object
req.open('GET','http://geocoder.us/service/csv/geocode?zip=95472',true); //Location and method
req.send(); //Send
req.onreadystatechange = function() { //When it's ready
if (this.readyState === 4) { //... which is code 4
console.log(this.responseText); //Then you have the responseText
}
}
This only works when the request is from the same domain, tho (for security purposes). If you want it to work on any domain, you'll have to use a proxy.
You should use Javascript to make an ajax request to that URL and it will return the information you want in a format you specify, usually JSON. Depending on what Javascript libraries you are/aren't using, there's different ways you could do that -- probably the most common would be to use jQuery to make your request. Here's info on that API:
https://api.jquery.com/jQuery.get/

HTML/Javascript - Get text from online file

I have info that Shoutcast outputs as an html file.
The html file looks like this: http://216.118.106.247:443/7.html.
Is there any way to get the last item in that list/array into Javascript as a string?
I want to output the song info in a html file, I assume that once I get it into JS as a string that I can use the document.write() function to output the code...
Thanks!
If you look at http://code.google.com/chrome/extensions/xhr.html, you'll need to set up cross-origin requests and then you should be able to use the XMLHttpRequest to fetch the data.
EDITED:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = process;
xhr.open("GET", "http://216.118.106.247:443/7.html", true);
xhr.send();
function process()
{
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
// resp now has the text and you can process it.
alert(resp);
}
}
Take a look at XMLHttpRequest aka Ajax requests.
There are a ton of libraries that make "Ajax" easy. Try this one:
http://www.prototypejs.org/api/ajax/request
There are limitations with what you can retrieve using ajax. Due to security issues your browser will not let javascript running on yourwebsite.com perform ajax requests to mywebsite.com.
Look up cross site scripting.
There are several methods out there for you to use. But make sure files are in the same server or folder.
Using XMLHttpRequest: http://www.javascripter.net/faq/xmlhttpr.htm
Using FileSystemObject: http://msdn.microsoft.com/en-us/library/czxefwt8(v=VS.85).aspx
Using a "helper" Java applet that reads a file or URL for your script
var fileContent='';
var theLocation='';
function readFileViaApplet(n) {
document.f1.t1.value='Reading in progress...';
document.ReadURL.readFile(theLocation);
setTimeout("showFileContent()",100);
}
function showFileContent() {
if (document.ReadURL.finished==0) {
setTimeout("showFileContent()",100);
return;
}
fileContent=document.ReadURL.fileContent;
document.form1.textarea1.value=fileContent;
}
Some other source to reference: http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm (many examples).
Just write a javascript file (js file) and include with the script tags.
This file will have your data like that.
<script type="text/javascript" src="data.js" >
where data.js can be..
var data[];
data[0]="something";
e.t.c
In your page (the one that calls data.js) the array data will be accessible.

Javascript cross-domain web request fails with Status=0?

EDIT: It's been pointed out below that this doesn't work because craigslist doesn't set an Allow-Cross-Domain header. OK, I'll buy that. Is there any other way to use javascript in firefox to download a page cross-domain then?
Yes, I know the following code does not work in IE. I know IE expects me to use XDomainRequest() instead. I don't care about that. This is firefox only.
I'm trying to do a cross-domain web request in firefox javascript. I keep getting a status of 0. Does anyone know why?
var url = "http://newyork.craigslist.org";
var xdr = new XMLHttpRequest(); //Yes, I know IE expects XDomainRequest. Don't care
xdr.onreadystatechange = function() {
if (xdr.readyState == 4) {
alert(xdr.status); //Always returns 0! And xdr.responseText is blank too
}
}
xdr.open("get", url, true);
xdr.send(null);
Shouldn't that work?
Craigslist doesn't allow cross-domain requests to it. It needs to send a proper Access-Control-Allow-Origin header.

Javascript XmlHttpRequest Issues

I created a html/javascript website running on an Apache Webserver on Mac OS X. This website consumes a .NET Webservice with JSON via XmlHttpRequest. This Webservice is running on a Windows Vista machine.
The website is accessible with this url: http://macintosh.companyname.local/~username/Sitename/index.html.
When I open the website on the Mac with Safari with this url I don't get any JSON data back from the Webservice.
When I open the website with the URL file://Users/username/Sites/Sitename/index.html it works perfectly.
My first thoughts are that is has something to do with XmlHttpRequest and it's security restrictions in many browsers, but I am not sure why it doesn't work when I call the site via the webserver instead of the absolute path to the html file.
Here the code I use to call the Webservice:
<div id="eigenRisico" class="panel" title="Eigen Risico">
<h2>Eigen Risico Per Polis</h2>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://webserviceurl/GetEigenRisicoVerzekerde", true);
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
var result = eval('(' +xhr.responseText+')');
var ihtml="";
var j = 0;
for(i = 0; i < result.d.length/2; i++) {
ihtml=ihtml+"<fieldset><div class='row'><label>Polisnummer:</label><span>"+result.d[j]+"</span></div>";
j++;
ihtml=ihtml+"<div class='row'><label>Resterend Eigen Risico:</label><span>&euro "+result.d[j]+"</span></div></fieldset>";
j++;
}
document.getElementById('eigenRisico').innerHTML = ihtml;
}
};
xhr.setRequestHeader("content-type", "application/json");
var postData = '{"bsn": "999999999"}';
xhr.send(postData);
</script>
</div>
Does somebody knows why this is happening?
You can't do cross-domain ajax requests
See http://en.wikipedia.org/wiki/Same_origin_policy
You can get around this by setting up a proxy page on your own domain that will take the request and redirect it, then redirect the output back to you.
Are you running PHP? or other server-side processing?
Edit
Just to clarify your original problem, when reading from file://, the security policy is different that from http://. the local resource is considered trusted, and as such the ajax request is allowed to go through. As a web address, it just looks like one website is doing things in your name that maybe it shouldn't.

Categories