Home

Ajax Image Upload With jQuery and PHP

Published on 7th Feb 2018 in 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.
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 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 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.

 

Download

Share It
Stay Connected
Like Us on Facebook