HTTP HEAD Request in Javascript/Ajax?
Asked Answered
G

3

64

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?

Granger answered 2/12, 2008 at 11:2 Comment(1)
Yes, check this...Grainfield
A
107

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

Acetate answered 2/12, 2008 at 11:11 Comment(10)
Thanks, sometimes the abstraction of a framework hides the underlying functionality!Granger
Any idea how cross-browser this is? The jQuery documentation states "Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers." api.jquery.com/jQuery.ajaxShamble
@outis: why this edit? I don't think stuff is getting better by this. I mean: the answer has served well for years, so why change it?Acetate
@doekman: Synchronous requests will block all JS-dependent tasks (Douglas Crockford once wrote that "Synchronous programming is disrespectful and should not be employed in applications which are used by people."). Think of all the people that unknowingly copied the example without thinking. For that reason, the answer has served poorly for years. The update both shows how to use asynchronous requests and makes explicit the fact that the example shouldn't be copied verbatim.Transported
@outis: I applaud your async change (and I don't question that). I didn't even see that change. I only saw you change the semantics/name of the function. I saw no reason for that (and I liked my simple, yet useful function), so I changed that back if you don't mind :-)Acetate
I applaud the fact that this answer is jQuery free. Even the simplest of JS questions on SO is almost always answered with a jQ solution.Anaheim
Any chance that b.c. this is just a HEAD request, one can go cross-domain?Rhodarhodamine
Note that this works OK when the page is behind a server - I found that the readyState is always 0 when loading the page straight off a file.Walt
Then you can use getAllResponseHeaders or getResponseHeader("header-name") on the this object (the XHR object) to get the actual headers received, as @Lawley mentioned.Ortegal
Checking for status code 404 only doesn't indicate that the URL exists. For example, it's perfectly valid to use 403 instead.Necker
B
4

The more modern approach is to use the Fetch API which replaced XMLHttpRequest.

e.g. (within an async function)

const url = "https://example.com";
const response = await fetch(url, { method: "HEAD" });
console.log(`Got status: ${response.status}`);

Baeyer answered 31/10, 2023 at 10:29 Comment(0)
L
-6

An XMLHTTPRequest object should have

getAllResponseHeaders();
getResponseHeader("header-name")

defined on it

Lawley answered 2/12, 2008 at 11:12 Comment(1)
Downvote: The answer seems to confuse the HTTP HEAD method with HTTP headers.Gnathonic

© 2022 - 2024 — McMap. All rights reserved.