HTTP HEAD Request in Javascript/Ajax? - javascript

Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?
My motivation is to conserve bandwidth.
If not, is it possible to fake it?

Easy, just use the HEAD method, instead of GET or POST:
function UrlExists(url, callback)
{
var http = new XMLHttpRequest();
http.open('HEAD', url);
http.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(this.status != 404);
}
};
http.send();
}
This is just a short example to show how to use the HEAD method. Production code may need more fine-grained callbacks for different result states (success, failure, timeout), and may use different event handlers (onload, onerror and ontimeout rather than onreadystatechange).

An XMLHTTPRequest object should have
getAllResponseHeaders();
getResponseHeader("header-name")
defined on it

Related

How to return a response from xmlhttprequest javascript

I don't know why this function is returning undefined. Please help me... Run Snippet
function xhr(url) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
return (this.response);
}
});
xhr.open("GET", url);
xhr.send();
}
let arr = xhr('https://reqres.in/api/users?page=2');
console.log(arr);
This is very very simple, Maybe you're new to Javascript, If you are not aware Js is an asynchronous language, it means that it would not block or wait for any function to complete which might be time consuming ( in this case a request to the server), This helps it to process other things meanwhile the request is taking place.
So in your case, it's creating the request to the server, but at the same time continues to execute your function and return the default value, i.e undefined, You can pass a callback to be called when the request is completed.
function callWhenFinished(arr) {
console.log(arr);
}
function xhr(url) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.addEventListener("readystatechange", function() {
if (this.readyState === this.DONE) {
callWhenFinished(this.response); // callback
}
});
xhr.open("GET", url);
xhr.send();
}
xhr('https://reqres.in/api/users?page=2');
you trying to make async request, but expect that it will work in synchronous way.
The way you solve your problem is:
use callbacks
use promises
use async/await (that's just wrapper of of promises)
i recommend you to use promises instead of XMLHttpRequest. it's easy to understand and it's modern way to work with requests.
related links here:
https://www.w3schools.com/js/js_callback.asp
https://www.w3schools.com/js/js_async.asp

Unable to capture response from an API in Javascript

I am using below code to capture response but unable to get, please let me know what I am missing here.
function testcall() {
var request = new XMLHttpRequest();
request.open('GET', 'http://demo8951713.mockable.io/fusionchart', true);
request.send();
var response = this.responseText;
alert(response);
}
testcall()
You have two problems.
First, this (in the context you are using it) does not refer to your XHR object.
Second, you are trying to read the response as soon as the request has been sent. You have to wait until the browser has received the response!
request.addEventListener("load", function () {
var response = this.responseText;
alert(response);
});
That change (moving the code to an event handler) also puts this in a context where it refers to the correct object.
Once you have fixed this, you are likely to want to try to return the value. Before you do, read this question.
you are missing the callback function
request.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.response);
}
}
for more details, refer https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response#Example

JavaScript GET responseText

I'm still learning the basics of JavaScript, and I'm trying to make a simple GET Http Request to return information from an API, but the responseText won't return. Here's the code:
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://api.apithis.net/dictionary.php?define=hi", true);
xhr.send();
console.log(xhr.responseText)
It is because you get response a bit later.
So you need to handle it async. To make this, u need to handle response in callback function, that will be fired at the moment you get response.
I reccomend you to use at least JQuery - it helps at start.
https://api.jquery.com/jquery.get/
if u still whant it using xhr (before xhr.send), i think it can be using:
xhr.onreadystatechange = function () { console.log(this.responseText) }

Empty response of XMLHttpRequest

In my Java Web application I am calling ajax request as below.
<script type="text/javascript">
function selectTableHandler() {
console.log("indise selectTableHandler");
var xhttp = new XMLHttpRequest();
var selectedTable = document.getElementById('selectTable').value;
alert(selectedTable);
xhttp.open("GET", "populateTableColumList.action?tablename="
+ selectedTable, true);
xhttp.send();
console.log(xhttp.responseText);
}
</script>
The Action is calling and returns status code 200 as below.
Remote Address:[::1]:8080
Request URL:http://localhost:8080/ReportBuilder/populateTableColumList.action?tablename=films
Request Method:GET
Status Code:200 OK
But, it gives empty response of XMLHttpRequest. The line console.log(xhttp.responseText); prints nothing. Also, there is no error in console log.
Any suggestions would be appreciated.
Thanks
You need to add a callback function to get the result of the ajax request.
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
Your ajax request is asynchronous. That means it returns the result some time LATER. You will need to install an event handler for onload or onreadystatechange to get the result.
There are plenty of Ajax tutorials on how to do this. Here are a couple useful references:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
If you want to use vanilla js you have to attach event handler onreadystatechange which will handle response, but my advice instead of use vanilla js, use library like jQuery to initiate the ajax request. It will be more easily and it will run without problems on all types of browsers. see here. If you want vanilla js, here is a sample snippet:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE ) {
if(xhttp.status == 200){
console.log(xhttp.responseText);
}
}
}

facebook graph api ajax XMLHttpRequest - Null result?

Summary: Keep getting null response despite public data and setting callback to enable cross domain JSON. Please help!
A similar question has been answered here
Using the new facebook graph api, ajax calls returns null (empty)
but I'm not using jquery and have tried to adapt my code to reflect that answer.
I'm trying to use a simple example to test a simple xmlhttprequest handler. I have this link in my page:
<a href='javascript:loadXMLDoc(\"https://graph.facebook.com/btaylor?callback=methodname\",\"\")'>AJAX LINK</a>
The callback=methodname parameter is to enable cross domain JSON
I'm using a generic XMLhttprequest builder:
var req; // Request object
function loadXMLDoc(url,params){
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader("Connection", "close");
req.send(params);
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader("Connection", "close");
req.send(params);
}
}
}
I then have a handler :
function processReqChange(){
if (req.readyState == 4) {
if (req.status == 200) {
alert("Done");
} else {
//alert("There was a problem retrieving the data:\n" + req.statusText);
alert("Status Code = "+req.status);
alert("There was a problem retrieving the data:\n");
alert("Failed : object = "+req);
alert(req.responseXML);
alert("Failed : response = "+req.responseText);
alert("Failed : status = "+req.statusText);
}
}else{
}
}
But I keep getting a null response (statusText OK, status code 0). Any ideas?
Thanks in advance
You can't make a cross-domain ajax request. Look into whether or not they support JSONP, or use the FB.api method from their javascript SDK
http://developers.facebook.com/docs/reference/javascript/FB.api
EDIT: I didn't read your post very thoroughly when I replied.
I see that you're adding the callback name to your ajax request, which isn't going to do any good because you're still making an XHR request, so it will still fail cross-domain. You seem to be misunderstanding how JSONP works.
Normally I'd just suggest using a framework like jQuery to abstract out the work that you shouldn't have to reinvent. If you're absolutely dedicated to doing this without jQuery, start by reading the wikipedia article on how JSONP works:
http://en.wikipedia.org/wiki/JSON#JSONP
The basic idea is:
Create a script node where the src attribute looks just like the URL you're trying to request now.
The server will respond with something like : methodname({"foo": "bar"}); instead of just JSON. Since this is being requested via a script node, your browser will execute the "methodname" function and pass in the results.
implement methodname(response) function to handle the response (i.e. do the work you intended to do in processReqChange)
Remove this line and try again:
req.setRequestHeader("Connection", "close");
It sets up the connection to close automatically, often before the send is complete.

Categories

Resources