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.
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.
This upload image example script has two files.
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.
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.
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….
Welcome Dinesh.
can you give me its corrosponding php file
Hi Deepak,
There are only two files and it is presented in the article.
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…
Hi Mani,
Welcome. Fingerprint recognition requires a hardware interfaced library. To integrate that into an application, PHP may be used.
keep up your work
Nice work!
Only say, please, change blog font, it’s very difficult to read
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.
thanks a lot for this code… really its working…
Welcome Kirti.
Thanks for sharing such nice article. It works like charm.
Welcome Nilesh.
Thanks for this useful code. There is a problem with end tag in the HTML code. Please fix it.
Thanks Pooya, I have fixed it. Thanks for your time.
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.
Thanks Ben. This PHP image upload script uses AJAX mechanism only.
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.
Hi Rajesh,
Thank you. Do you want to store the image in database or just store the image url. Here is an example https://phppot.com/php/mysql-blob-using-php/
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!
Welcome Mika.
wow thanks a lot Vincy. i find this method easy.. thanks
Welcome Faisal.
can you give this code in java?
Amit, sorry I do not code in Java :(
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?
Hi Mexanots (Nice name :-)
What you have asked is available as part of another tutorial that is linked in this article.
nice to meet you vincy
Nice to e-meet you too Kunal :-)
Mam i need same type but small change as gives image upload path complete with directory location
Sivaramaiah, you just need to supply the path you need on upload.
Thank you, I want to update image using Ajax in Laravel. Please help
Sure, I will add a new article. Keep watching Ayush.
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.
Hi Danish,
Sure, I will try to add MySQL code to insert the uploaded image URL.
Please write a tutorial blog on upload image on server using php after cropping using cropper.js and/or rcrop.js.
Thanks.
Sure Satish, I have noted your request and will try to write soon on it.
Vincy can u help me its upload but i cant see the image and nor it is saved somewhere can u help me plz
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.
thank you,
i want to preview first before uploading…what should i do with the code..
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.
I use this offline on xamp server it work correctly,
But on my online hosted website it does not work!
Hi Hadi,
In that case, you need to check for file upload permissions on your hosted server.
Thank you, I want to update image using Ajax in php. Please help
Hi Haris,
Upload or update? This article is to upload the image.
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
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.
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);
}
Yes Ben. That would be a nice addition to the code. Thank you for the contribution.
You shouldn’t call it “PHP” Ajax Image Upload if you cannot include the PHP file contents with the tutorial -_-
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.
Hello, can you share your full php file for this
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.
Very to the point and straight forward php and javascript. Easy to follow for beginners. Thanks for this tuto.
Welcome Rodriguez. Thank you for the nice words.
Wonderful, the best and simple code for AJAX image upload. Thank you.
Thank you James.
Life saver may you see beautiful days
Thank you Michaella.
how to upload an image using ajax without action field and without reloading the page in PHP
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.
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.
Sure Aunbandh. I will write the code and inform you.
Thanks for sharing the image upload code. Cool!
Welcome Jose.
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” />
Thank you Reza for the contribution.
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
Thank you Francis for the nice words.