URL in Ajax open() - javascript

This is my first Ajax program and I can't fix the code because I'm not sure where/what the problem is.
The error(which I'm unable to interpret) while using the debugger is,
XMLHttpRequest cannot load http://localhost/function.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
function calling()
{
var x;
if (window.XMLHttpRequest) {
x = new XMLHttpRequest();
} else {
x = new ActiveXObject("Microsoft.XMLHTTP");
}
x.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200)
{
document.getElementById("block").innerHTML = this.responseText;
}
};
x.open("GET", "http://localhost/function.txt",true);
x.send();
}
function.txt
<html>
<head></head>
<body>
<h2>Ajax is working</h2>
</body>
</html>

Is your js located at the same location as your function.txt?
For more information about CORS, have a look at this link: https://www.html5rocks.com/en/tutorials/cors/
UPDATE:
This works for me, I think there is maybe something with your Apache settings...
function calling()
{
var xhr = new XMLHttpRequest(),
method = "GET",
url = "function.txt";
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
alert(xhr.responseText);
}
};
xhr.send();
}
calling();

You cannot make Ajax calls to a url from a different domain if said domain does not explicitly allow it (via 'Access-Control-Allow-Origin' header).
Your error means that you're making your Ajax call from another domain. If your function.txt file is located at the same location as your js, try using relative path in your .open().

You are attempting a CORS request, which is unsafe and is prohibited by browsers by default. If you are in control of the target site, you can enable CORS. If that's not the case, then you will need to write a page which will be used as a proxy, that is, you will send the request to this page instead of the target site's page. The page, on its turn will send the request to the target page and send the output to the browser. While this is a workable solution you will need to make sure that all the absolute paths of the target site are handled well.

Related

Getting HTML Source Code via XMLHttpRequest [JavaScript]

XMLHttpRequest works for first url but it doesn't work for second url.I think this function doesn't work for dynamic web pages.I also tried ajax to get html source but it didn't work too.What can I do?How can I change this code to work for second url?
<script language="Javascript" type="text/javascript">
function getSource(url)
{
var req = new XMLHttpRequest();
req.open(
"GET",
url,
true);
req.onreadystatechange = statusListener;
req.send(null);
function statusListener()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
var doc=req.responseText;
alert(doc);
}
}
}
}
url1 = "https://pages.github.com/";
url2 = "https://stackoverflow.com/";
// This code WORKS
getSource(url1);
// This code DON'T WORK
getSource(url2);
</script>
I ran your code in a JSFiddle, and I got an error message saying it is a CORS issue. You can view these error messages by opening the Javascript console in your browser of choice.
CORS (Cross-Origin Resources Sharing) issues arise when you don't have the sufficient permission to access resources between different domains. Each web server has policies set up that determine the rules for accessing these files, and Stack Overflow's security settings are set up to disallow that kind of access to their site. You can read more about CORS here.

How to check webpage is available or not using javascript

I want to make a web page request only if that web page is available. I have written my app using angularjs + javascript. Is there any way to determine whether a webpage is available or not using javascript ?
If the page in question is on a different origin, you can't without using a server somewhere or relying on the other page implementing Cross-Origin Resource Sharing and supporting your origin, because of the Same Origin Policy.
If the page in question is on the same origin, you can do an ajax call to query it:
var xhr = new XMLHttpRequest();
xhr.open("HEAD", url);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
// It worked
} else {
// It didn't
}
}
};
xhr.send();
You can make an AJAX request with XMLHttpRequest, but instead of POST or GET, you should use the HEAD HTTP verb.

Simple code for request url and show response code | javascript | jquery

How can to request url or website address and show response code with javascript or jquery?
i.e
request www.google.com
if (response_code = 200) {
print "website alive"
} else if (response_code = 204) {
print "not found";
}
I'm assuming from the jquery tag that you mean to do this in a browser, not from a server running NodeJS or similar (although there is a NodeJS module for jQuery).
Although you can request URLs and see the response code using the XMLHttpRequest object, the Same Origin Policy will prevent your accessing virtually any sites other than the one the page itself was loaded from. But if you're pinging the server your page was loaded from to make sure it's still there, you can do that:
function ping(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("get", url);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) { // Request is complete
callback(xhr.status); // Tell the callback what the status code is
}
}
}

What am I missing in the XMLHttpRequest?

I'm completely new to the javascript and ajax world but trying to learn.
Right now I'm testing the XMLHttpRequest and I can't make work even the simplest example. This is the code I'm trying to run
<script type="text/javascript">
function test() {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200){
var container = document.getElementById('line');
container.innerHTML = xhr.responseText;
} else {
alert(xhr.status);
}
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);
}
</script>
And I always get the alert with the status 0. I've read tons of webs about this and I don't know what am I missing. I will appreciate any help, thanks!
You are running into the Same Origin Policy.
Unless your code is actually running on www.google.com (which is unlikely), this is going to error.
Also, and while this isn't causing you a problem at the moment, it is poor practice and can lead to race conditions, you are using globals all over the place.
Make the xhr variable local to the function
var xhr = new XMLHttpRequest();
And refer to it with this inside the onreadstatechange method.
if (this.readyState == 4 && this.status == 200){
// etc etc
Following from David's answer:
You have to use a relative path to stay within the same origin policy. Otherwise most browsers will simply return an empty responseText and status == 0.
As one possible workaround, you could set up a very simple reverse proxy (with mod_proxy if you are using Apache). This would allow you to use relative paths in your AJAX request, while the HTTP server would be acting as a proxy to any "remote" location.
The fundamental configuration directive to set up a reverse proxy in mod_proxy is the ProxyPass. You would typically use it as follows:
ProxyPass /ajax/ http://google.com/
In this case, the browser would be requesting /ajax/search?q=stack+overflow but the server would serve this by acting as a proxy to http://google.com/search?q=stack+overflow.
In addition to the same origin policy issue, your alert is in an illogical place. When you use XMLHttpRequest, the function assigned to xhr.onreadystatechange will be called whenever readyState changes. readyState should change (in theory) from 0 (initialized) to 1 (sent) to 2 (loading) to 3 (interactive) to 4 (finished).
What your code does is check the readyState and see if the request is finished (if (xhr.readyState == 4)), and if not, alert the HTTP status code. Since the request hasn't been sent yet (or has just been sent), there shouldn't be an HTTP status yet.
Ideally, you should move the alert inside the if block, so it lets you know when it finishes.

Prevent redirection of Xmlhttprequest

Is it possible to prevent the browser from following redirects when sending XMLHttpRequest-s (i.e. to get the redirect status code back and handle it myself)?
Not according to the W3C standard for the XMLHttpRequest object (emphasis added):
If the response is an HTTP redirect:
If the origin of the URL conveyed by the Location header is same origin
with the XMLHttpRequest origin and the
redirect does not violate infinite
loop precautions, transparently
follow the redirect while observing
the same-origin request event rules.
They were considering it for a future release:
This specification does not include
the following features which are being
considered for a future version of
this specification:
Property to disable following redirects;
but the latest specification no longer mentions this.
The new Fetch API supports different modes of redirect handling: follow, error, and manual, but I can't find a way to view the new URL or the status code when the redirection has been canceled. You just can stop the redirection itself, and then it looks like an error (empty response). If that's all you need, you are good to go. Also you should be aware that the requests made via this API are not cancelable yet. They are now.
As for XMLHttpRequest, you can HEAD the server and inspect whether the URL has changed:
var http = new XMLHttpRequest();
http.open('HEAD', '/the/url');
http.onreadystatechange = function() {
if (this.readyState === this.DONE) {
console.log(this.responseURL);
}
};
http.send();
You won't get the status code, but will find the new URL without downloading the whole page from it.
No you there isn't any place in the API exposed by XMLHttpRequest that allows you to override its default behaviour of following a 301 or 302 automatically.
If the client is running IE on windows then you can use WinHTTP instead to set an option to prevent that behaviour but thats a very limiting solution.
You can use responseURL property to get the redirect destination or check whether the response was ultimately fetched from a location you accept.
This of course means the result is fetched anyway, but at least you can get the necessary info about the redirect destination and for example detect conditions when you would like to discard the response.
I extended user's answer to include an abort() call. It seems like this prevents the server from sending too much data when all you want is the redirect url.
var url = 'the url'
var http = new XMLHttpRequest();
http.open('GET', url);
http.onreadystatechange = function() {
if (this.readyState === this.DONE) {
console.log(this.responseURL)
this.abort() // This seems to stop the response
}
}
http.send()
In real life I wrapped the above code in a promise, but it made the code hard to read.
Also, I don't understand why getting the redirect url needs to be this difficult, but that is a question for another time and place.
It is not possible to handle redirect or 302 status at client side as answered in other comments. However you can prevent redirection. To do that you can set request header "X-Requested-With" with "XMLHttpRequest"
xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
This should be done after open but before send. Example below
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
reqObj.success(JSON.parse(this.responseText))
} else if (this.status != 200) {
reqObj.error(this.statusText)
}
};
xhttp.open(reqObj.type, reqObj.url, reqObj.async);
xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhttp.send();

Categories