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

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

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

difference between youtube's request and mine

i want to make a script that makes every video's comment section look like the ones that still have the old kind.
for example, videos on this channel:https://www.youtube.com/user/TheMysteryofGF/videos
in Firebug, in the Net tab, i noticed the comment JSON file's URL it is requested from is different.
i tried to run a code on the youtube watch page which would request the file the same way, but it doesnt work, and in firebug it says it was forbidden.
the URL is the same, they are both POST, and i cant figure out what is different. i can even resend the original request in firebug and it works... so anyway, here is a code i tried on a video with "1vptNpkysBQ" video url.
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://www.youtube.com/watch_fragments_ajax?v=1vptNpkysBQ&tr=time&frags=comments&spf=load', function(data) {
alert('Your public IP address is: ' + data);
}, function(status) {
alert('Something went wrong.');
});
You are using Ajax to get data. Ajax has 1 restriction: You can only get data from your own server. When you try to get data from another server/domain, you get a "Access-Control-Allow-Origin" error.
Any time you put http:// (or https://) in the url, you get this error.
You'll have to do it the Youtube way.
That's why they made the javascript API. Here is (the principal of) how it works. You can link javascript files from other servers, with the < script > tag
So if you could find a javascript file that starts with
var my_videos = ['foo', 'bar', 'hello', 'world'];
then you can use var my_videos anywhere in your script. This can be used both for functions and for data. So the server puts this (dynamically generated) script somewhere, on a specific url. You, the client website can use it.
If you want to really understand it, you should try building your own API; you'll learn a lot.
Secondary thing: Use GET.
POST means the client adds data to the server (example: post a comment, upload a file, ...). GET means you send some kind of ID to the server, then the server returns its own data to the client.
So what you are doing here, is pure GET.

How to read JSON data, that is sent from Android, using Javascript?

I have created a mobile application that scans the surrounding Bluetooth devices and I am able to put the devices into an array list.
Now, using the http POST method, I have to send a JSONObject having this array list to a url and even for this I have written an expected code on the android app(I am sure this code will work because I have already worked on this using POST method to URL's and displaying the response on the activity).
But, how to listen the JSONObject, sent by any android app to the URL, parse it and show it on that particular URL's webpage ?
(In short I am looking for a Javascript code which can handle this and show the list.)
if you already have the URL where the JSON is being posted to you can do:
plain js:
var request = new XMLHttpRequest();
request.open('GET', 'URL', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
with jquery:
var getData = $.getJSON('URL');
getData.done(function(data){
// you have access to data here
});

Load image and remove when authentification is required

I am grabbing some (random) images from a search machine and display them to the users. The problem is: It may happen that some images require a http authentification (username/password). I dont want to have those images... they should be removed without displaying the popup where you can enter the username and password.
Actually I am using simple jquery methods to display my images.
var displayNode = ....
....
var m_img = $("<img />", {src : "...."});
m_img.bind('error', function (e) {
$(this).remove();
});
displayNode.append(m_img);
Now I load the image directly and if an error occurs it will be removed. But.. when server sends back a HTTP (Basic) Authentification flag this is of course not an error. Hence there is an input prompt. When I click on "cancel" the propmt closes, jquery treats this as an error and removes the image.
So.. what is the best way to check if there is authentification and if not display it to the user?
You can make a HEAD request that only returns headers, then check the headers for the authentication header before actually making the request:
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
You would use this method to first check the headers, then if OK, get the image. You'll have to test it with your protected resource, I'm not sure what the browser will do when requesting just the HEAD and I don't have a local protected resource to test against (CORS got me on the online resources I was trying to test against). Fiddle:
var basicAuthProtectedURL = 'http://fiddle.jshell.net';
var xhr = new XMLHttpRequest();
xhr.open("HEAD", basicAuthProtectedURL, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.getAllResponseHeaders()); //all headers
console.log(xhr.getResponseHeader('Content-Type')); //just the one you want
if (xhr.getResponseHeader('WWW-Authenticate')) {
console.log('I got the authentication header, skip this request.');
} else {
console.log('no header, resource unsecure');
}
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
http://jsfiddle.net/5z5bnwgz/
Post back how it goes!

Categories