Ajax File Upload with PHP and jQuery

Are you looking for a file upload using Ajax in PHP? Uploading a file through Ajax is a preferred way. It adds a better user experience to the application. In this article, I show you how to upload files through Ajax with PHP and jQuery.

File or Image uploading is a common task for developers. There are several situations 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 File Upload using Ajax?

The major reason for performing file uploads with Ajax is you don’t want to refresh a page after file uploads. There is no point in loading a whole page if not necessary. If you are doing it then you are adding an extra load on a server unnecessarily.

File uploading using Ajax reduces this server load and gives a better user experience. It works in the background without interfering with the other content of a page.

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 id="frmUpload">
    <p><input type="file" name="file" class="file" required /></p>
    <input type="submit" name="submit" value="Submit" />
</form>

As I am going to write a little bit of JavaScript code, I provided the class file and id frmUpload to the file input and HTML form respectively. These attributes would act as an identifier in JavaScript.

JavaScript Code

Next, write a JavaScript code that will perform the following tasks.

  • Take a file input from the HTML form.
  • Send this form data to the server-side script via Ajax.
  • Receives the response from the server.
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
    $(function() {
        $('#frmUpload').on('submit', 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.');
                        }

                        $("#frmUpload")[0].reset();
                    }
                });
            }
            return false;
        });
    });
</script>

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

PHP Code

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

<?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 the uploads directory. If this folder does not exist, it creates the folder 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 *