PHP AJAX Image Upload

by Vincy. Last modified on August 10th, 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 quite frequently.

In this tutorial 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. In a previous tutorial, we have seen PHP image upload example without AJAX.

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.

PHP AJAX Image Upload Output

On submitting the form with the selected image file, the AJAX script will be executed. In this PHP AJAX image upload example script, 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.

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 example script has two files.

  1. First one is for UI to invoke the backend script without form submit.
  2. The second file is the backend PHP script, that does the actual image upload. It writes to the disk and responds with the image output.

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>

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

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.

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

PHP AJAX script to upload image

To upload image using AJAX, you need a backend script that does the processing. This file upload.php here in this example uploads 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.

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

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.

Comments to “PHP AJAX Image Upload”

  • Dinesh Sharma says:

    Thanks a lot Vincy!!!

    yesterday i was searching for such type of coding for by website for images upload but i want something more in this coding i want to resize the image size before submit. Please help me….

  • Mani says:

    Thank u. Your code really helpful for me.
    i have one more doubt. want develop a php project for fingerprint recognition. This possible or not. I was searched more sites, but most members say not possible. So i Want clear answer for this question vincy…

  • Edu says:

    Nice work!

    Only say, please, change blog font, it’s very difficult to read

    • Vincy says:

      Thank you Edu. The font is planned to be changed along with the coming overall site redesign. Will do it soon in the coming month.

  • kirti says:

    thanks a lot for this code… really its working…

  • NILESH says:

    Thanks for sharing such nice article. It works like charm.

  • Pooya says:

    Thanks for this useful code. There is a problem with end tag in the HTML code. Please fix it.

  • Ben says:

    Most people mentioned that you can’t do this via ajax but I tried this and works fine for me. Thank you for the simple and nice code.

  • Rajesh says:

    This code is very helpful but I need one more thing, I want to store image in MySql database and fetch them again according to need. but thank you for this code.

  • mika says:

    oh)

    Oh, wow! You are damn genius! Two days I’m trying to find some solution, i used jquery form library, visited many sites, but decided the only problem here! Thank you!

  • faisal says:

    wow thanks a lot Vincy. i find this method easy.. thanks

  • Amit Kumar Raikwar says:

    can you give this code in java?

  • mexantos says:

    how about if we want to preview image before send request to server, i mean we want to check look and feel image in the browser before actually send or upload to the server.
    addition to this could i do upload multiple images to server with this?

    • Vincy says:

      Hi Mexanots (Nice name :-)

      What you have asked is available as part of another tutorial that is linked in this article.

  • Kunal Dongre says:

    nice to meet you vincy

  • s.sivaramaiah says:

    Mam i need same type but small change as gives image upload path complete with directory location

  • Ayush Srivastava says:

    Thank you, I want to update image using Ajax in Laravel. Please help

  • mohd danish says:

    will you please share your mysql code with me. i am trying inserting operation in this thats work but image name is not getting into database.

  • Satish Kumar Sharma says:

    Please write a tutorial blog on upload image on server using php after cropping using cropper.js and/or rcrop.js.
    Thanks.

  • Jay says:

    Vincy can u help me its upload but i cant see the image and nor it is saved somewhere can u help me plz

    • Vincy says:

      Hi Jay,

      You may have insufficient file upload / write permissions on your server disk. Check that. Other than this, the code should work as it is simple and straightforward.

  • wilda says:

    thank you,
    i want to preview first before uploading…what should i do with the code..

    • Vincy says:

      Hi Wilda,

      This code shows the uploaded image as preview. What you can do is, use this output as a preview. Then add an additional button, in this screen and call the upload.php on click of it. You may have to supply the real location in the upload.php.

  • Abdul Hadi says:

    I use this offline on xamp server it work correctly,
    But on my online hosted website it does not work!

  • Muhammad haris says:

    Thank you, I want to update image using Ajax in php. Please help

  • Mangal Eswari says:

    Hello Vincy, I’m using image compressor for user upload purpose. but after compressed image, only have blob HTTP url…I can’t upload image to my server…. Could you help me….How to solve that issue

    • Vincy says:

      Hi Mangal,

      I couldn’t get a grasp of your query, can you please elaborate. You may send a detailed email to me, it is off topic for this article. Thanks.

  • Ben says:

    Really appreciate the tutorial, one addition I might add is that the html being returned may need filtered. Especially if your form is being generated and processed in the same php file.

    If you’re in WordPress (like me) it would mean you have something like this in your AJAX call.

    url: ”,

    Unfortunately that means all the html from the page will be displayed inside your target after the form is submitted. If you just want to display a portion of the returned html you can filter it using something similar to what I have below.

    success: function (data) {
    var filtered_data = $(data).find(‘#id-from-returned-data’);
    $(‘#html-output’).html(filtered_data);
    }

  • Shreyansh says:

    You shouldn’t call it “PHP” Ajax Image Upload if you cannot include the PHP file contents with the tutorial -_-

    • Vincy says:

      Hi Shreyansh,

      PHP file is included. I present (free) all the files in all my tutorials. In this article, only two PHP files are used, index.php and upload.php, both are given in the tutorial already.

  • Joseph says:

    Hello, can you share your full php file for this

    • Vincy says:

      Hi Joseph,

      Yes it is shared. The PHP AJAX image upload example requires only two files and it is presented in full in the article. Apart from this there are no files.

  • Rodriguez says:

    Very to the point and straight forward php and javascript. Easy to follow for beginners. Thanks for this tuto.

  • James says:

    Wonderful, the best and simple code for AJAX image upload. Thank you.

  • Michaella says:

    Life saver may you see beautiful days

  • sachin says:

    how to upload an image using ajax without action field and without reloading the page in PHP

    • Vincy says:

      Hi Sachin,

      This example PHP script given in this article demonstrates the same. It uploads image using AJAX without action field and without reloading the page. You should run the PHP script and check it out.

  • anubandh singh says:

    can you make a form with 4 images to upload into mysql with image validation of four images. i can surely pay for that
    email the zip to my email.

  • Jose says:

    Thanks for sharing the image upload code. Cool!

  • reza says:

    hi
    thank you for this code
    I change upload.php file :

    50000) {
    echo “Sorry, your file is too large.”;
    $uploadOk = 0;
    }
    else
    {
    if($_FILES[“userImage”][“type”] != “jpg” && $_FILES[“userImage”][“type”] != “png” && $_FILES[“userImage”][“type”] != “jpeg”
    && $_FILES[“userImage”][“type”] != “gif” ) {
    echo “Sorry, only JPG, JPEG, PNG & GIF files are allowed.”;
    $uploadOk = 0;
    }
    else
    {
    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="”
    class=”upload-preview” />

  • chijioke francis says:

    Much thanks to you vincy, i started using your blog back then in 2016 when i started learning web dev till date when i take up some professionally jobs and i must you are really great in what you do.

    i really appreciate

Leave a Reply

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

↑ Back to Top

Share this page