PHP Ajax Image Upload With Preview Example

Hi Guys,

In this tutorial, i will give you simple example of ajax image upload with preview in php. Uploading image via an jquery AJAX in php. I have added code for doing PHP image upload with AJAX without reloading the page.

xI use jQuery AJAX to implement image upload. There is a form with file input field and a submit button. On submitting the form with the selected image file, the AJAX script will be executed. In this code, it sends the upload request to PHP with the uploaded image. PHP code moves the uploaded image to the target folder and returns the image HTML to show the preview as an AJAX response.

The following code shows the HTML for the image upload form. On submitting this form the AJAX function will be called to send the request to the PHP image upload code.

Create Form form.php
<html>
<head>
   <title>PHP AJAX Image Upload</title>
   <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
   <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css">
</head>
<body>
<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>
         <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>
               <div class="form-group">
                  <input name="userImage" type="file" class="form-controller" />
               </div>
               <input type="submit" value="Submit" class="btn btn-success" />
            </form>
         </div>
      </div>
   </div>
</div>
</div>
</body>
<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>
</html>
Create Upload Fille upload.php
<?php
  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; ?>" />
<?php
  }
    }
      }
?>

it code is a redy php ajax image upload with preview and the run code.

it will help you..

Post a Comment

0 Comments