Ajax Image Upload With jQuery and PHP

In this tutorial, we will see how to upload file/image and get a preview without refresh the page using ajax with jQuery and PHP.

We have already seen image/file upload snippet with PHP in the previous tutorial.

In this tutorial, we submit forms 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 the file name to get image view. This snippet can be used to upload files, images and videos.

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.

Table of Contents

HTML

<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"  />
</form>
<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 the server, a set of key/value pairs (i.e. form fields and values).

JavaScript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$(document).ready(function(e){

$('#myform').on('submit',function(e){

e.preventDefault();   
 $.ajax({
url:  'upload.php',
type: 'post',
data: new FormData(this), 
cache: false,
contentType:  false, 
processData:  false,
success: function(response)
{
$('#preview').html(response);
},
error: function(e){} 
});
});
});
</script>

PHP

<?php
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">';
   else:
   echo "File not uploaded!";
   endif;
   
endif;
?>

Thatโ€™s it. How is it easy to upload images or files using ajax 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 the comment box.

[sociallocker]Download[/sociallocker]

Leave a Comment