How to use CORS? - javascript

I am trying to implement Ajax calling and i came across the follwing code:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "www.google.com", true);
xhttp.send();
}
</script>
</body>
</html>
I am tring to access the URl but ended up in error saying "XHR cannot load".
I know it is something related with CORS. I went through several pages but i am finding it difficult to understand the issue. can somebody please explain and resolve this issue?? Will be helpul

Google dont allow cross domain access to their search engine. Your method seems ok, its just the url you are trying to access doesn't allow your domain.
Try it with a file hosted on your local machine

Related

XMLHttpRequest loads XML from local server but not from external server?

I've made various attempts to load XML from external servers, but without success.
The first example loads the XML perfectly when I have the XML document on my server, but not when I try loading the same XML from the external server.
The second example is loading XML from on an external server, but the data that loads on my page doesn't resemble XML.
Am I missing something in my XMLHttpRequest, or is this the Cross Origin problem?
EDIT: The second example was solved by changing responseText to responseXML, however the first example already has responseXML and yet it doesn't work. Why won't the first example function in the same manner as the second example?
first example
var n = document.getElementById("search");
n.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET","https://www.w3schools.com/xml/books.xml", true);
xhttp.send();
}
function myFunction(xhttp) {
var a = n.value;
var xmlDoc = xhttp.responseXML;
const { value } = search;
const foundState = [...xmlDoc.querySelectorAll('title')].find(possibleMatch => possibleMatch.textContent === value);
const unit = foundState.parentElement;
console.log(unit.innerHTML);
document.getElementById("titleNode").innerHTML = unit.children[0].textContent;
document.getElementById("authorNode").innerHTML = unit.children[1].textContent;
document.getElementById("yearNode").innerHTML = unit.children[2].textContent;
}
<input type="text" name="search" id="search" placeholder="type 'r'" list="searchresults" autocomplete="off" />
<datalist id="searchresults">
<option value="Everyday Italian">001</option>
<option value="XQuery Kick Start">010</option>
<option value="Learning XML">110</option>
<option value="Harry Potter">101</option>
</datalist>
<button id="myButton" type="button"
onclick="loadDoc('https://www.w3schools.com/xml/books.xml', myFunction)">Submit
</button>
<p>Title node: <span id="titleNode"></span></p>
<p>Author node: <span id="authorNode"></span></p>
<p>Year node: <span id="yearNode"></span></p>
second example
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", "https://data.cityofnewyork.us/api/views/kku6-nxdu/rows.xml", true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("demo").innerHTML =
xhttp.responseXML;
}
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button"
onclick="loadDoc('ajax_info.txt', myFunction)">Change Content
</button>
</div>
Your hunch is correct, this is the Same-Origin Policy in action! Some servers are set up to allow Cross-Origin Resource Sharing (CORS), but that is pretty rare. If you would like to set up one of your websites/servers to allow another Ajax request access, you can follow this MDN guide.
Edit: Scott Marcus is correct about your code.
About your second question:
I ran your code and got this error in the console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.w3schools.com/xml/books.xml. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
w3schools does not have CORS enabled.
Take a look at this thread and the links posted there to find a way to circuimvent the Same Origin Policy.

Simple JavaScript to Servlet POST or GET doesn't work

The JavaScript below was adapted from W3Schools. Basically, I just added the URL path to my Servlet in the JS code below.
The Servlet on the server simply returns one of two strings:
(1) GET: Hello from Ajax Server! (**GET**)
(2) POST:Hello from Ajax Server! (**POST**)
The code for the doGet() and doPost() Servlet methods is to just create a PrintWriter from the Response and write a string to it.
The JavaScript below does nothing when I run it by clicking the button. I've omitted the URL to the actual server in the JS code below since that's the customer's site.
Any suggestions would be most welcome.
Thanks,
<!DOCTYPE html>
<html>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xmlhttp.responseText;
};
xhttp.open("GET", "<path_to_server>:8080/AjaxSvr/ajax", true);
xhttp.send();
}
</script>
</body>
</html>

parse xml with javascript for html

I am trying to get some information from the Yahoo Console for weather conditions. The xml result tree from Yahoo looks like this: result tree
I am able to get things that are only one level deep with the code I have. My variable 'beta' is for the title which works beautifully. The second variable is 'alpha' which will not work. I believe it has to do with how I call for it 'item.condition.temp' and with the node values.
I am very new to this so please list any sources you use as it will help me going forward.
<!DOCTYPE html>
<html>
<head>
<p id="alpha"></p>
<p id="beta"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open('GET', 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2444827&diagnostics=true', true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
document.getElementById('beta').innerHTML =
xmlDoc.getElementsByTagName('title')[0].childNodes[0].nodeValue;
document.getElementById('alpha').innerHTML =
xmlDoc.getElementsByTagName('item.condition.temp')[0].childNodes[0].nodeValue;
}
</script>
I would suggest adding &format=json to your URL to make it this:
https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2444827&diagnostics=true&format=json
Then parse the resulting JSON which is a more JavaScript way of doing it.

What is wrong with this code using ajax?

I'm new to coding and now I'm trying to write a code that gets the text data form a file and replace the present text with the new one. I'm using AJAX to do the task but the problem is first I'm getting the error message and then expected answer The error message is what I have included in the code to display when there is error. Even though i'm getting the desired answer I want to know why the error message is displayed. Here is my code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script>
function loadXML() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest;
}
else {
xmlhttp = new ActiveXObject("MICROSOFT.XMLHTTP")
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
}
else {
alert(" there is a error in your code");
}
}
xmlhttp.open("GET","robots.txt", true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<p id="p1">This is Text</p>
<button id="b1" onclick="loadXML()">Click me </button>
</body>
</html>
The problem is your if-block in onreadystatechange. During the request and response, xmlhttp.readyState changes multiple times and onreadystatechange is called every time this happens.
If you do it like this, it may work:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 ) {
if( xmlhttp.status == 200 ) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
} else {
alert(" there is a error in your code");
}
}
It is simpler, however, to use the other event-methods like onload and onerror, as described here.
1- include 1 jQuery file jquery-1.9.0.js same as jquery-1.9.0.min.js but jquery-1.9.0.min.js is minified file
2- what is the Error message from javaconsole log ?
3- you are using jQuery so why you are working with XMLHttpRequest when jQuery $.get already using best of HttpRequest for all browsers
you can replace your JS code with this
<script type="text/javascript">
$( document ).ready(function() {
$.get('robots.txt',function(data){ $('#p1').html(data) });
});
<script>
Are you using a webserver ? Ajax doesn't work from local file url : 'file://...'
alert(" there is a error in your code");
Actually there is no error in your code. xmlhttp.onreadystatechange is called in different states of the request. Thats why you check for xmlhttp.readyState == 4. Learn more about the different stages here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
So your code is running fine, you just alert an error message, that is not an error at all.

not entering in "xmlhttp.onreadystatechange=function() {"

I am following my old question post that I suddenly enter in a new problem that is: my code is not entering in this line "xmlhttp.onreadystatechange=function()". I also checked by marking alert. so I unable to understand. can somebody tell me why this is not happening?
<html>
<head>
<script>
function changeThis(){
xmlHttp = new XMLHttpRequest();
var formInput = document.getElementById('theInput').value;
/* formInput will be undefined */
document.getElementById('newText').innerHTML = formInput;
/* also undefined */
// var xmlHttp = null;
xmlhttp.onreadystatechange=function() //help
{
alert("y"); // not entering help?????
if (xmlhttp.readystate==4 && http.status==200)
{
document.getElemenById('newText').innerHTML=xmlhttp.reponseText;
}
if(xmlhttp.status == 404)
{
var temp = "NO file found";
document.getElementById('newText').innerHTML=temp;
}
xmlHttp.open( "GET", "file2.php", true);
xmlHttp.send();
}
}
</script>
</head>
<body>
<p>You wrote: <span id='newText'></span> </p>
<textarea id="theInput" style="height:200px;">Write Here</textarea>
<input type='button' onclick='changeThis()' value='See what you wrote'/>
</body>
</html>
Move this:
xmlHttp.open( "GET", "file2.php", true);
xmlHttp.send();
outside of the onreadystatechange handler; your current code won't try to submit the HTTP request until after the HTTP request is already making progress. (Hat-tip to judder for editing your question to indent your code properly, making this problem obvious.)
Edited to add: Also, as Pavlo points out, you need to consistently write xmlHttp. JavaScript variable-names are case-sensitive, so xmlhttp is a completely different variable.

Categories