PHP AJAX Image Upload

by Vincy. Last modified on May 24th, 2022.

AJAX image upload in PHP is simple if you use the right technique. You can get this done in less than five minutes. When you build websites routinely, image upload is one of the feature that you come across frequently.

To upload image using AJAX, you need not write a complex code. Uploading image via PHP AJAX function is easy and simple to implement in a few lines of script. I will present you a simple example using PHP AJAX for image upload.

In this example, I have added code for doing PHP image upload with AJAX without form submit by not reloading the page. I will use jQuery AJAX to implement image upload. There is a form with file input field and a submit button.

AJAX action will point to a URL that has a PHP script. This PHP file will process the AJAX request in the backend and will send a response which is the result of the image upload.

On submitting the form with the selected image file, the AJAX script will be executed. In this PHP AJAX image upload example code, it sends the upload request to PHP with the uploaded image.

PHP AJAX Image Upload Output

PHP code moves the uploaded image to the target folder and returns the image HTML to show the preview as an AJAX response.

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

PHP AJAX image upload UI with jQuery

This upload image using AJAX example script has two files. First one is for UI and has the AJAX script to invoke the backend script without form submit. The second file is the backend PHP script, that does the actual image upload and writes to the disk and responds with the image output.

I have used AJAX call and without form submit. For PHP AJAX call, I have used jQuery to make the invocation. I have included the jQuery AJAX JavaScript code at the bottom of the file just before HTML body for better page loading performance.

jQuery script version used is 3.6 via CDN. You can use any version of jQuery from very old to the latest possible and it should work without any issues. jQuery AJAX image upload requires core jQuery features and nothing fancy is used here.

I have kept the CSS styles to as minimum as possible, in order to give you freedom in integration with your application. Your application styles can takeover the over styles.

For PHP AJAX image upload, enctype='multipart/form-data' is not required as we are not submitting via form post. We are using PHP AJAX data transfer and multipart form data is not required for the image upload.

index.php

<html>
<head>
<title>PHP AJAX Image Upload</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
	crossorigin="anonymous"></script>
<style>
#targetLayer {
	font-family: arial;
	margin-bottom: 20px;
}

.btn-upload {
	padding: 5px 30px;
	border-radius: 4px;
	margin-top: 20px;
	color: #2f2f2f;
	font-weight: 500;
	background-color: #ffc72c;
	border: 1px solid;
	border-color: #ffd98e #ffbe3d #de9300;
}
</style>
</head>
<body>
	<form id="image-upload-form" action="upload.php" method="post">
		<div id="targetLayer">Image Preview</div>
		<div>
			<input name="userImage" type="file" class="inputFile" />
		</div>
		<div>
			<input type="submit" value="Upload" class="btn-upload" />
		</div>
	</form>
	<script type="text/javascript">
    $(document).ready(function (e) {
    	$("#image-upload-form").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(data)
    	    	{
    		  	  console.log("error");
                  console.log(data);
    	    	}
    	   });
    	}));
    });
</script>
</body>
</html>

PHP AJAX script to upload image

upload.php

To upload image using AJAX, you need a backend script that does the processing. PHP AJAX invokes a backend script to upload the image without form submit. This file upload.php here in this example does the backend processing of uploading the image file. On AJAX invocation, this PHP script moves the file to the disk and returns the HTML img element that points to the uploaded image file.

After successful image upload, AJAX success function will print the uploaded image HTML. Then, this will be added to a target DIV to show the preview for the users. For PHP AJAX image upload, you can copy these two files and add it to your projects. It is a simple integration process.

<?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="image-preview" src="<?php echo $targetPath; ?>"
	class="upload-preview" />
<?php
        }
    }
}
?>

Comments to “PHP AJAX Image Upload”

Leave a Reply

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

↑ Back to Top

Share this Article