PHP AJAX Image Upload

by Vincy. Last modified on June 1st, 2021.

Uploading image via an AJAX function is easy and simple to implement in out page. In a previous tutorial, we have seen PHP image upload example without AJAX.

In this example, 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.

View Demo

After uploading an image via AJAX, we are showing preview for the uploaded image in the target div as shown below.


HTML Image Upload Form

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.

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

PHP Image Upload via AJAX Method

This code shows the ajax() function used to send the file upload request by posting the FormData instance. In PHP, it uploads the file to the specified path.

After successful image upload, it will print the uploaded image HTML as the AJAX in response. Then, this will be added to a target DIV to show the preview for the users.

<script type="text/javascript">
$(document).ready(function (e){
url: "upload.php",
type: "POST",
data:  new FormData(this),
contentType: false,
cache: false,
success: function(data){
error: function(){} 	        

View DemoDownload

Comments to “PHP AJAX Image Upload”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top