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
Related
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.
I'm trying to figure out how to make a DELETE request using just Javascript. I have a service written in Java Spring where the controller for the url that I am working on has method = RequestMethod.DELETE. My url is, say, http://192.168.50.51/my-service/deleteLocation/{value1}/{value2}/{value3}. In my JavaScript, I have an AJAX function like so:
ajaxFunction : function(url, callback, httpMethod) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var jsonParse = JSON.parse(xhttp.responseText);
callback(jsonParse);
}
}
xhttp.open(httpMethod, url, true);
xhttp.send();
}
When I want to use the DELETE url, I have an event handler attached to a button that runs this method:
deleteConfirm : function() {
var valuel = this.value1;
var value2 = document.getElementById('element-id').getAttribute('data-element');
var value3 = document.getElementById('element-id').getAttribute('data-element2');
var url = 'http://192.168.50.51/my-service/deleteInfo/' + value1 + '/' + value2 + '/' + value3;
var httpMethod = 'DELETE';
var deleteCallback = function() { alert('deleted!'); }
this.ajaxFunction(url, deleteCallback, httpMethod);
}
However, I keep getting an error in my console: my-javascript.js:59 DELETE http://192.168.50.51/my-service/deleteInfo/123456789/123-456-7AB/12699 406 (Not Acceptable).
I've read that XMLHttpRequest only accepts GET and POST. How do I go about making a delete request using just JavaScript?
Given the information, it looks like your browser is actually making a DELETE request, because the server gave you back a 406 (Not Acceptable) response. It wouldn't do that if your client never sent the request in the first place. This means that the server received your DELETE request and decided it wouldn't process it. So you'll need to look at the server's API to see what gives you HTTP406 and what needs to be different about your request to make it work.
A good way to debug these kinds of things is through your browsers developer tools. Most browsers have a tab in there that shows you the HTTP requests and responses that the browser made. It will make it easier for you to verify these things, going forward.
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
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.
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
}
}
}