PHP AJAX Image Upload

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

image-thumbnails

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

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){
$("#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>

Output

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

php-ajax-image-upload-output

View DemoDownload

This PHP code tutorial was published on January 3, 2014.

↑ Back to Top