PHP Ajax Image Upload With Preview Example

PHP Ajax Image Upload With Preview

Hello dev’s, Today now in this tutorial, i will give you a simple and short example of ajax image upload also with preview in php. Uploading image by using an jquery AJAX in php. So i will give you code for doing PHP image upload with AJAX without reload the page.Here we know PHP Ajax Image Upload With Preview.

Here I will use jQuery AJAX to implement any image upload. So there is a form with file input field and also from submit button. Now on submitting the form with the selected image file, the AJAX script will be executed. So in this code, it sends the upload request to PHP also with the uploaded image. Now PHP code will moves the uploaded image to our target folder and also returns the image HTML to show with the preview as an AJAX response.

Now the following code will show the HTML for the image upload form. On we submitting this form with the AJAX function will be called to send the request to the PHP image upload code.

Create Form

   <title>PHP AJAX Image Upload</title>
   <script src=""></script>
   <link rel="stylesheet" type="text/css" href="">
<div class="container">
   <div class="col-md-6 offset-md-3">
      <div class="card">
         <div class="card-title p-1 bg-success">
            <h6>PHP AJAX Image Upload</h6>
         <div class="card-body">
            <form id="uploadForm" action="upload.php" method="post">
               <div class="col-md-12 bg-light mb-2 text-center">
                  <div id="targetLayer">No Image</div>
               <div class="form-group">
                  <input name="userImage" type="file" class="form-controller" />
               <input type="submit" value="Submit" class="btn btn-success" />
<script type="text/javascript">
$(document).ready(function (e) {
   $("#uploadForm").on('submit',(function(e) {
           url: "upload.php",
         type: "POST",
         data:  new FormData(this),
         contentType: false,
           cache: false,
         success: function(data)
              error: function() 

Create Upload Fille

  if(is_array($_FILES)) {
    if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
      $sourcePath = $_FILES['userImage']['tmp_name'];
      $targetPath = "images/".$_FILES['userImage']['name'];
      if(move_uploaded_file($sourcePath,$targetPath)) {
<img class="img-fluid" width="100%" height="100" src="<?php echo $targetPath; ?>" />

Read Also : How to run laravel project without php artisan serve command ?

Thanks for read. I hope it help you. For more you can follow us on facebook.


About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →