Ajax Image Upload With jQuery and PHP

In this tutorial we will see how to upload file/image and get preview without refresh page using ajax with jQuery and PHP. We have already seen image/file upload snippet with PHP in previous tutorial. In this tutorial we submit form using jQuery and ajax. Form data sent to PHP code where image moved and upload to target folder. On success, get ajax response as image path with file name to get image view. This snippet can be used to upload file, image and video.Ajax image upload with jQuery and PHP.

Ajax image upload with jQuery and PHP

Also read:

File Uploading in PHP

Upload multiple images with Jquery and PHP

Let us see the snippet.

<form method="post" enctype="multipart/form-data" id="myform">
<label class="input-file">Upload Image<input type="file" name="image" /></label>
 <input type="submit" value="Submit"  />
<div id="preview"></div>

e.preventDefault(); is used here to prevent a submit button from submitting a form. Image is sent using Jquery with ajax by FormData. FormData is used to sent form data to server, a set of key/value pairs (i.e. form fields and values).


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>


url:  'upload.php',
type: 'post',
data: new FormData(this), 
cache: false,
contentType:  false, 
processData:  false,
success: function(response)
error: function(e){} 


if(isset($_FILES)) :
$path  = "upload/";
$tmp   = $_FILES['image']['tmp_name'];
$name  =    $_FILES['image']['name'];

   if(move_uploaded_file($tmp,$path.$name)) :
   echo '<img src="'.$path.$name.'" height="100" width="100">';
   echo "File not uploaded!";

That’s it. How is it easy to upload image or file using aajx with jquery and PHP. If you liked this article 🙂 please share with your friends and colleagues 🙂 . If you have any query feel free to write in comment box.


Leave a Reply

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