How to upload Image using AJAX and Javascript?

upload Image using AJAX and Javascript
upload Image file using AJAX and Javascript

In the previous tutorial, we learned how to upload Image using AJAX and PHP and now in this tutorial, we’ll learn how to upload Image using AJAX and Javascript. We will also look into uploading file(s) via AJAX and JQuery in the very next post.

So, in this case, we are going to create an HTML form and write our AJAX code using Javascript in the same HTML file and one .php file to write server-side code for uploading a file & storing it at the desired location.

In the previous post, we performed all the validation operations in .php file itself which in programming terminology called server-side validation. Here, in the post, we’ll apply the same validation on the client-side on the uploaded file.

First, we’ll go through the HTML code from which we’ll upload file.

upload Image using AJAX and Javascript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload File in PHP</title>	
</head>
<body>
	<div class="form">
		<input type="file" id="upload_file" accept="image/jpeg, image/png"/>
		<button id="submit_button">Upload File</button>
	</div>
</body>
</html>

So, main fields that are responsible for uploading file is-

<input type="file" id="upload_file" accept="image/jpeg, image/png"/>

Here, we have defined input type as file (type="file") which is used for uploading file(s).
Another attribute accept="" is used to set what file types are permitted for uploading.

Next is the button, which is the click action and clicking on it will upload the file to its respective location(of course after performing JS operations)

Let’s see the Javascript code that will perform AJAX call and send the file to the server-side.

// predefined file types for validation
var mime_types = [ 'image/jpeg', 'image/png' ];
    
var submit_button = document.querySelector('#submit_button');
    
submit_button.addEventListener('click', function() {
    
    // check if user has selected file OR not
    var selected_file = document.querySelector('#upload_file');
    if(selected_file.files.length == 0) {
        alert('Please select file to upload.');
        return;
    }

    // Get the file uploaded
    var file = selected_file.files[0];
    
    // validate MIME type
    if(mime_types.indexOf(file.type) == -1) {
        alert('Please select jpeg or png files only.');
        return;
    }

    // max 5 MB size allowed
    if(file.size > 5*1024*1024) {
        alert('Please select file having less than 5MB size.');
        return;
    }

    // upload file
    var form_data = new FormData();

    // append selected file to the formData object
    form_data.append('file', document.querySelector('#upload_file').files[0]);

    var request = new XMLHttpRequest();
    request.open('post', 'uploadFile.php'); 

    // send POST request to server
    request.send(form_data);
});

In the above code, we have first initialized two variables. mime_types & submit_button. These variables contain file types to be permitted for upload and button click event respectively.

var mime_types = [ 'image/jpeg', 'image/png' ];
    
var submit_button = document.querySelector('#submit_button');

Next, we will use addEventListner() method whose task is to attach an event handler to the specified element. Here, in this case, we have click as an event handler and this event handler is attached to our submit_button element.

submit_button.addEventListener('click', function() {});

Once button is clicked and Javascript captured that event then it will go inside the condition and will get upload_file dom element which is nothing but the uploaded file element. Then in the very next line we will check if the file is uploaded or not by measuring length of the uploaded file. If length is == 0 then we’ll show an Error message to the user and program will exit.

    // check if user has selected file OR not
    var selected_file = document.querySelector('#upload_file');
    if(selected_file.files.length == 0) {
        alert('Please select file to upload.');
        return;
    }

If the user uploads file and its length is greater than 0 then it will jump to the next line of code. In the next line, we’ll store the uploaded file in the var file variable. Next we’ll evaluate whether that MIME type of that file is matching with the ones which we stored in the mime_types global array. If that does not match then we’ll show an error message to the user.

    var file = selected_file.files[0];

Next, we will check the file size of the uploaded is greater than 5MB. IF that uploaded file size is greater than this size then we’ll show such Error message to the user.

    if(file.size > 5*1024*1024) {
        alert('Please select file having less than 5MB size.');
        return;
    }

Once everything validated then we’ll create an object that represent HTML form data using new formData(); Once this object is created then we’ll call append method of this formData Class and pass name value parameters. These passed key value are nothing but the file and uploaded file in binary format itself.

    var form_data = new FormData();

    form_data.append('file', document.querySelector('#upload_file').files[0]);

Now, we’ll create XMLHttpRequest() object and will call open method and will pass the method and file path to which data will be sent.

    var request = new XMLHttpRequest();

    request.open('post', 'uploadFile.php'); 

And finally we will send formData to the upload.php file using send method of the XMLHttpRequest class.

    request.send(form_data);

This was this uploaded file will be send to the server side scripting language and server side language i.e., PHP will capture all these passed information into Global Variable $_FILES. This variable contains all the information about the uploaded file.