JavaScript AJAX Check if a file exists via a HEAD request


This function executes an AJAX request using the HEAD method allowing us to check whether a file exists in the directory given as an argument. It also enables us to launch a callback for each case (success, failure).

function fileExists(dir, successCallback, errorCallback) {
    var xhttp = new XMLHttpRequest;

    /* Check the status code of the request */
    xhttp.onreadystatechange = function() {
        return (xhttp.status !== 404) ? successCallback : errorCallback;

    /* Open and send the request */'head', dir, false);