PHP Ajax Image Upload With Preview Example

Admin   PHP   1250  2021-03-18 14:30:06

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.

I 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




<title>PHP AJAX Image Upload</title>

<script src=""></script>

<link rel="stylesheet" type="text/css" href="" target="_blank" rel="nofollow" >



<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; ?>" />






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

it will help you.