How to upload Image file using AJAX and jQuery

In PHP you can easily upload any type file on the server using move_uploaded_file() method.

But it requires form submit for uploading the selected file.

If you want to store image file and display preview without reloading the whole page then you need to use jQuery AJAX.

Send the selected file using FormData object in AJAX request.

How to upload Image file using AJAX and jQuery


Contents

  1. HTML
  2. CSS
  3. PHP
  4. jQuery
  5. Conclusion

1. HTML

Create a <form > element where added <img >, file element and a button.

Image preview display in <img> after successfully upload using jQuery.

Completed Code

<div class="container">
    <h1>AJAX File upload</h1>

    <form method="post" action="" enctype="multipart/form-data" id="myform">
        <div >
            <img src="" id="img" width="100" height="100">
        </div>
        <div >
            <input type="file" id="file" name="file" />
            <input type="button" class="button" value="Upload" id="but_upload">
        </div>
    </form>
</div>

2. CSS

/* Container */
.container{
    margin: 0 auto;
    border: 0px solid black;
    width: 50%;
    height: 250px;
    border-radius: 3px;
    background-color: ghostwhite;
    text-align: center;
}
.container h1{
    background-color: cornflowerblue;
    color: white;
    font-weight: normal;
    margin-top: 0px;
    padding: 15px 5px;
    text-align: center;
}

/* file */
#file{
    border: 2px solid gray;
    border-radius: 3px;
    color: black;
    padding: 10px 5px;
}

/* Button */
.button{
    border: 0px;
    background-color: deepskyblue;
    color: white;
    padding: 5px 15px;
    margin-left: 10px;
}

3. PHP

Create an upload.php file and upload directory for storing image files.

Check the file extension if it is valid then store the file and return the file location.

Completed Code

<?php

/* Getting file name */
$filename = $_FILES['file']['name'];

/* Location */
$location = "upload/".$filename;
$uploadOk = 1;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);

// Check image format
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
 && $imageFileType != "gif" ) {
 $uploadOk = 0;
}

if($uploadOk == 0){
 echo 0;
}else{
 /* Upload file */
 if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
 echo $location;
 }else{
 echo 0;
 }
}

4. jQuery

On the upload button click get the selected file and create a FormData object.

Append file in FormData object.

Send an AJAX request where pass the fd object and on successful callback check the response is 0 or not. If it is does not 0 then update the <img > source otherwise alert('file not uploaded') message.

Completed Code

$(document).ready(function(){

    $("#but_upload").click(function(){

        var fd = new FormData();
        var files = $('#file')[0].files[0];
        fd.append('file',files);

        $.ajax({
            url: 'upload.php',
            type: 'post',
            data: fd,
            contentType: false,
            processData: false,
            success: function(response){
                if(response != 0){
                    $("#img").attr("src",response);
                }else{
                    alert('file not uploaded');
                }
            },
        });
    });
});

5. Conclusion

Use FormData object to store the file and pass in the AJAX request for upload it.

In the PHP file access the file using $_FILES.

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  

3 Comments

  1. Alessandro B. said:

    Thanks for this good how-to.
    After some hours of search on the net this article has resolved all my problems 🙂

    December 12, 2017
    Reply
  2. Jesús said:

    Thank you! It was very useful!

    May 13, 2018
    Reply
  3. Paul said:

    This is an awesome article, after days of efforts, this was the best solution I found

    May 18, 2018
    Reply

Leave a Reply

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