javascript XMLHttpRequest returning status of 0 [duplicate] - javascript

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 6 years ago.
I am trying to call a REST API with JavaScript and XMLHttpRequest.
The URL is: "http://quotes.stormconsultancy.co.uk/random.json"
This works from the browser window, but when I try to run it as javascript in the browser, it always returns a status of 0
(Even when I substitute the URL with any another URL for a simple GET request - for e.g. http://www.yahoo.com, I still get the same result.
Here is the code:
(function callRestAPI() {
var request = new XMLHttpRequest();
var url = "http://quotes.stormconsultancy.co.uk/random.json";
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
alert("The response was: " + request.responseText);
} else if (request.status === 0) {
alert("The response was a status code of 0");
}
}
};
request.open("GET", url, "false");
request.send();
})();
I am at a loss on how to figure this out. Any help would be appreciated.
Thanks,
Jay
(Note: I get the same result with Firefox 47 and Chrome 51

Isn't this a Cross-Origin Request issue? Since you're calling the URL in ajax from another domain it gets blocked, thats why when you're doing it from the browser window it works (same domain) but from where you're hosting your script it doesn't?

Cross-Origin Request, the Server has to provide some whitelist to let you do what you want, read here:
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Related

URL in Ajax open()

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.

How to perform Ajax call with JSONP request in JavaScript? [duplicate]

This question already has answers here:
JavaScript XMLHttpRequest using JsonP
(5 answers)
How to make a JSONP request from Javascript without JQuery?
(12 answers)
Closed 6 years ago.
I use pure JavaScript to make ajax call in another domain (cross-domain).
So i need to specify the dataType. But i don't know, where to specify ?.
I use the following to make ajax call with javascript:
var xmlhttp = new XMLHttpRequest();
var url = 'www.mydomain.com/path/to/reach';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log('Log : ' + url + ' || Updated.');
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
url = url + '?callback=my_callback_method';
xmlhttp.open("GET", url, true);
xmlhttp.send();
Also i make dummy callback,
function my_callback_method(res){
//
}
But, it won't work. I get error as Reason: CORS header ‘Access-Control-Allow-Origin’ missing.
What's wrong with my code ?
Is it possible ?
Any Solutions ?
(I need Solution for JavaScript Only !)
I get error as Reason: CORS header ‘Access-Control-Allow-Origin’
missing.
This is because you're using XMLHttpRequest and usage of XMLHttpRequest requires CORS. The JSONP technique doesn't involve usage of XMLHttpRequest. The trick in JSONP is to create a script tag and let a browser load that script:
var script = document.createElement('script');
script.src = '//domain.com/path/to/jsonp?callback=my_callback_method'
document.getElementsByTagName('head')[0].appendChild(script);
Also, you need to create a global function, in your case its my_callback_method, and call it from the jsonp script.
Certainly, you server side should have implementation that when a request to //domain.com/path/to/jsonp is obtained, it should return a js document with a call to a global function specified in callback=my_callback_method:
my_callback_method()

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
}
}
}

How to validate a url address ( not syntax but the network )?

I want to validate a url address actually returns a valid page.
There are two approaches one could take.
IFrame - create and iframe that points to the url
Ajax - create an ajax request to the url and look at the status codes - Here is some fiddling
The Ajax method is not working because it always returns a status code of 0 for cross domain requests whether the page is there or not.
The IFrame method is not working b.c. I can not find a mechanism for capturing status or errors of the frame.
Most of the google hits I'm getting are for syntax checking.
Fiddle Code for Ajax
var urlTest = function (url) {
var xhr = new window.XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
console.log('readyState | status : ' + this.readyState + ' | ' + this.status);
if (this.readyState === 4) {
if (this.status === 200) {
// console.log('4 | 200');
// xhr.responseText;
}
}
};
xhr.send(null);
}
urlTest('http://www.google.com'); // cross domain always give status 0
You may circumvent the CORS restrictions imposed on browsers by means of a proxy as suggested here (without jsonp):
https://en.m.wikipedia.org/wiki/JSONP

XMLHttpRequest only works in IE

I am using the XMLHttpRequest object for my AJAX calls which has been working fine across browsers with a callback handler I have created to return JSON based on the request type and arguments etc.
But I am now integrating an external RESTful API to return a JSON string and for some reason it only works for me in IE (tested in IE 8). Using fiddler 2 I have determined that the API is returning the correct data.
I get the XMLHttpRequest.readyState of 4 but XMLHttpRequest.status only returns 0 for Chrome, Safari and FF. I read that sometimes when using a local server (test server) you always get a status of zero so I bypassed my check for status but still got a blank string for XMLHttpRequest.responseText.
function ajaxRequest(requestType,url) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
switch (requestType)
{
case 5:
//Home postcode search
showAddresses("home", xmlhttp.responseText);
break;
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
You should upgrade to jQuery as it will handle this request for nearly all browsers. But if you really want to know how to use XMLHttpRequest across all browsers, here's some code that seems to do the trick: https://github.com/ilinsky/xmlhttprequest/blob/master/XMLHttpRequest.js
Or, just pick apart jQuery's implementation.
http://api.jquery.com/category/ajax/
Hope this helps.
My issue was that I was using an external API and xmlHttpRequest only allows you to makes calls on the same server. I moved my data call into my server code and got the response from my callback handling page instead of going straight out to the API.

Categories