JavaScript AJAX Check if a file exists via a HEAD request

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


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

Got any JavaScript Question?