Breaking News
Loading...
,

PHP AJAX Image Upload

Share on Google Plus

PHP AJAX Image Upload


In this tutorial let us learn about how to upload an image file using PHP and AJAX. We are using jQuery AJAX to send image file to the server side PHP script.
Steps for PHP AJAX Image Upload,
  1. Add jQuery library
  2. Create HTML for image upload form
  3. Send file data to PHP via AJAX
  4. Write PHP script to upload image

PHP Example to Upload Image

HTML code for the form containing file input is,
<form id="uploadForm" action="upload.php" method="post">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
On submit, the AJAX call will be triggered to send form’s file input to the PHP pageupload.php. The script is,
<script type="text/javascript">
$(document).ready(function (e){
$("#uploadForm").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data:  new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}          
});
}));
});
</script>
This AJAX call includes several options URL, Type, data and more. we are sending image file data by instantiating FormData. The success/failure handlers are triggered based on the result of the upload request.
Note
  • Import jQuery library before calling jQuery AJAX handler.
  • Find PHP script and css by extracting the source code zip added with this tutorial.

Output

Initially the form will be,
image_upload_from
After uploading image via AJAX, we are loading the image to the target layer in the left side of the above form. 

You Might Also Like

0 comments

About me


Like us on Facebook