I will show you how to upload a file using PHP, AJAX and jQuery without page refresh. This file upload tutorial example is very helpful to implement the upload functionality. In this example the file is selected using the browse button and file is uploaded to the ‘uploads’ directory. PHP script stores the file into the defined location and returns response as a success or failure message from the PHP script. As a validation step I have added only to check if you have selected a file for uploading or not.

You may read also  AJAX Multiple Files Upload using PHP, jQuery and AJAX File Upload using Codeigniter, jQuery

Following steps are required in order to upload a file

1.  Include jQuery library.

2.  HTML page with upload field.

3.  jQuery Ajax code.

3.  PHP script to store the file.

 

Step 1. Include jQuery library into <head/> section of the HTML page

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

Step 2. Put the below upload field inside <body/> tag in HTML page

<p id="msg"></p>
<input type="file" id="file" name="file" />
<button id="upload">Upload</button>

Step 3. Add below jQuery, AJAX code immediate after the jQuery library inside <head/> section of the HTML page

<script type="text/javascript">
            $(document).ready(function (e) {
                $('#upload').on('click', function () {
                    var file_data = $('#file').prop('files')[0];
                    var form_data = new FormData();
                    form_data.append('file', file_data);
                    $.ajax({
                        url: 'upload.php', // point to server-side PHP script 
                        dataType: 'text', // what to expect back from the PHP script
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function (response) {
                            $('#msg').html(response); // display success response from the PHP script
                        },
                        error: function (response) {
                            $('#msg').html(response); // display error response from the PHP script
                        }
                    });
                });
            });
</script>

Step 4. Create upload.php file with below source code

<?php

if (isset($_FILES['file']['name'])) {
    if (0 < $_FILES['file']['error']) {
        echo 'Error during file upload' . $_FILES['file']['error'];
    } else {
        if (file_exists('uploads/' . $_FILES['file']['name'])) {
            echo 'File already exists : uploads/' . $_FILES['file']['name'];
        } else {
            move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
            echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
        }
    }
} else {
    echo 'Please choose a file';
}
    
/* 
 * End of script
 */

If we combine the steps 1, 2, 3 and 4 then the full source code would be as shown below in a file called file_upload_ajax.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>File upload using PHP, jQuery and AJAX</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function (e) {
                $('#upload').on('click', function () {
                    var file_data = $('#file').prop('files')[0];
                    var form_data = new FormData();
                    form_data.append('file', file_data);
                    $.ajax({
                        url: 'upload.php', // point to server-side PHP script 
                        dataType: 'text', // what to expect back from the PHP script
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function (response) {
                            $('#msg').html(response); // display success response from the PHP script
                        },
                        error: function (response) {
                            $('#msg').html(response); // display error response from the PHP script
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <p id="msg"></p>
        <input type="file" id="file" name="file" />
        <button id="upload">Upload</button>
    </body>
</html>

Now if you run the above file then you will see below output in the browser

ajax file upload using php, jquery

If you try to upload file without selecting any file then you would see error message “Please choose a file”.

If the file successfully uploaded then you will see success message “File successfully uploaded : uploads/<some-file-name>“.

If the file you are trying to upload already exists then you will see a message “File already exists : uploads/<some-file-name>“.

Hope you have got an idea how to upload file using PHP, AJAX and jQuery.

Thanks for reading.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

4 thoughts on “AJAX File Upload using PHP, jQuery

Leave a Reply

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