Ajax File Upload With PHP And jQuery

Are you looking for a file upload using Ajax in PHP? Uploading a file through Ajax is trending stuff nowadays. It adds a better user experience on a website. In this article, I show you how to upload files through Ajax with PHP and jQuery.

File/Image uploading is a regular task for developers. There are several cases where you need to build file uploading functionality. Some of the common examples are uploading profile photos, slider images, testimonials, portfolios, carousels, etc.

Why need of File Upload using Ajax?

The major reason for performing file upload through Ajax is you don’t want to refresh a page after file uploading. And it is obvious. There is no point in the loading of a whole page if not necessary. If you are loading a page after file upload then you are adding extra load on a server.

File uploading using Ajax reduces the unnecessary load on a server and gives a better user experience on the website.

So without any further delay let’s start with the code.

File Upload using Ajax with PHP and jQuery

Let’s start by creating a form that has a file input and the submit button. Add the below HTML code in your file say index.php.

<form>
    <p><input type="file" name="file" class="file" required></p>
    <input type="submit" name="submit" class="submit" value="Submit">
</form>

As I am going to write a little bit of JavaScript code, I added the class ‘file’ and ‘submit’ to the file input and submit button respectively. These classes act as an identifier for form elements.

JavaScript Code

Next, write some JavaScript code which will give an Ajax call to a server-side and handle the response.

<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
    $(function() {
        $('.submit').on('click', function() {
            var file_data = $('.file').prop('files')[0];
            if(file_data != undefined) {
                var form_data = new FormData();                  
                form_data.append('file', file_data);
                $.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    contentType: false,
                    processData: false,
                    data: form_data,
                    success:function(response) {
                        if(response == 'success') {
                            alert('File uploaded successfully.');
                        } else {
                            alert('Something went wrong. Please try again.');
                        }
 
                        $('.file').val('');
                    }
                });
            }
            return false;
        });
    });
</script>

In the above JavaScript code, I am sending file content to the ajax.php file and also handling the response.

PHP Code

At this stage, we are done with sending the file contents to the server-side. Now create a file ajax.php where we have to write the PHP code which uploads files on a server.

ajax.php

<?php
if (!file_exists('uploads')) {
    mkdir('uploads', 0777);
}
 
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
 
echo "success";
die();

The above PHP code first checks for ‘uploads’ directory. If this directory does not exist then it creates it and uploads the file inside this folder.

I hope you can now easily implement file uploading using Ajax on your website. I would like to hear your thoughts in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

6 thoughts on “Ajax File Upload With PHP And jQuery

  1. $arr_file_types = [‘image/png’, ‘image/gif’, ‘image/jpg’, ‘image/jpeg’];
    Parse error: syntax error, unexpected ‘[‘ in /Applications/AMPPS/www/upload/index.php on line 39

    I have an error ? Why ? i don’t understand

    1. It seems you are running an older version of PHP. Try $arr_file_types = array('image/png', 'image/gif', 'image/jpg', 'image/jpeg');

  2. Great tutorial!

    If I could criticize one thing it would be the following code;
    $(‘.submit’).click(function() {

    The (Better?) method would maybe look like;
    $(“.submit”).on(“click”, function() {

    Other than that, awesome work!

Leave a Reply

Your email address will not be published. Required fields are marked *