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.
Related
This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 6 years ago.
I am a JavaScript beginner have just been introduced to concepts of web services, one-page sites and AJAX. In the assignment I got, one of the problems is to access a web service (using AJAX js) on a different domain. There is a side note in the assignment explaining something called "CORS" which enables the browser to access a foreign web service using the origin header. Setting the valuse of the origin header is, if I understood correctly, not controlled by the user.
So, I wrote the following code:
HTML:
<html>
<INPUT TYPE = "button" id = "button" VALUE = "Access web service"><br>
<div id = "message"></div>
<script src = "zaz2.js" type = "text/javascript"></script>
</html>
JavaScript:
function check()
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4 && ajax.status == 200)
{
document.getElementById("message").innerHTML="OK.";
document.getElementById("message").style.backgroundColor="green";
}
else document.getElementById("message").innerHTML = "Error";
}
ajax.open("GET", "http://zamger.etf.unsa.ba/provjeriGrad.php", true);
ajax.send();
}
var button = document.getElementById( "button");
button.addEventListener("click" , check);
The code simply prints "OK" if accessing the web service was successful and "Error" if it was not.
The web service you see here is an example one I got to use for the assignment. It allows even "localhost" domains to access it, which is what I am doing (Windows OS and WAMPSERVER).
Currently, I only get the "Error" printed in my div. I am not sure if my code is wrong, or web service simply doesn't work.
I would like your advice regarding my code, if it needs improvement. If web service is the problem, I would be grateful if you could provide me with an example of a working web service, just so I can test my code.
Thank you in advance.
Try to load he page of the URL in your browser. It is the target website that has to decide whether it allows your CORS or not.
Here: http://www.test-cors.org/
you can test requests to given targets and see which allows it and which not. Anyway, if a site does not allow CORS, then you will not be able to reach it cross-domain.
I saw this great API (http://www.dictionaryapi.com/products/api-collegiate-dictionary.htm) by merriam webster that returns an XML file with all the details in it including definitions and pronunciations.
This API requires a key so i registered and got a key for my account.
I am making the request using Javascript(XHR) but the status returned is zero.
Then i googled the error it said that it may be because my request is going from a "file:///" protocol instead of "http://", so i installed LAMP stack on my PC then hosted the file on my localhost server and even then no luck.
Another thread said that i cant make cross domain requests.
Please can you help me. Below is my HTML code from which i call function in my javascript file.
<html>
<head>
<script type="text/javascript" src="context-script.js">
</script>
</head>
<body>
<h1>Merriam Webster</h1>
<div>
<b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span><br/>
<b>Sound:</b><span id="sound"></span><br />
</div>
<script>
callOtherDomain();
</script>
</body>
</html>
Below is my JAvascript file context-script.js code:
function callOtherDomain()
{
invocation = new XMLHttpRequest();
var url = 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/happy?key=8f394b2c-77e8-433d-b599-f3ca87660067';
//url="note.xml";
if(invocation)
{
invocation.open('GET', url, true);
invocation.withCredentials = "true";
invocation.onreadystatechange = handler;
invocation.send();
alert("ref");
}
}
function handler(evtXHR)
{
if (invocation.readyState == 4)
{
alert("erg");
if (invocation.status == 200)
{
var response = invocation.responseXML;
document.getElementById("to").innerHTML=
response.getElementsByTagName("dt")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
response.getElementsByTagName("dt")[1].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
response.getElementsByTagName("dt")[2].childNodes[0].nodeValue;
}
else
alert(invocation.status);
}
else
dump("currently the application is at" + invocation.readyState);
}
But when i change the URL to "note.xml" which is locally stored on the localhost code works absolutely fine.
Thanks in advance.
While this question is several years old, I worked with dictionaryapi.com previously and the solution is two-fold:
Your first step to host on a local server was right on (localhost:8000 or http://127.0.0.1:8000). I prefer using the Python SimpleHTTPServer, started in the root directory of the page you're trying to host with whichever CLI tool you're most familiar/comfortable with, py -m http.server.
After that, just complete a jQuery call using ajax, get, or XMLHttpRequest—whichever you prefer. For example:
$.ajax({
url: 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/[YourWord]?key=[YourKeyHere],
method: "GET"
}).done(function(response){
console.log(response);
});
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.
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.
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.