Ajax Image Upload using PHP and jQuery is very important topic nowadays because everybody wants to save their data without refreshing the page. Today we are going to generate an Ajax based image uploader, which means the image file will be uploaded to server using Ajax request, without reloading the page. We are using jQuery AJAX to send image file to the server side PHP script. We can also use HTML5 File API to check file size and image type before uploading.
Steps for PHP AJAX Image Upload
1. Add jQuery library
2. Create HTML for image upload form
3. Send file data to PHP via AJAX
4. Write PHP script to upload image
Ajax Image Upload using PHP and jQuery
HTML code
1 2 3 4 5 6 | <div class="img-upload"> <h1 style="text-align: center;">Ajax Image Upload</h1> <form class="frmUpload" action="" method="post"><label>Upload Image:</label> <input id="userImage" class="user-image" name="userImage" required="" type="file" /> <input class="btn-upload" type="submit" value="UPLOAD" /></form> <div class="img-preview"> </div> <div class="upload-msg"> </div> </div> |
It’s the simple form and full page HTML code includes jQuery library & our AJAX file upload script and necessary CSS (Download zip in the end).
AJAX Code
On submit, the AJAX call will be triggered to send form’s file input to the PHP page upload.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $(document).ready(function (e) { $(".frmUpload").on('submit',(function(e) { e.preventDefault(); $(".upload-msg").text('Loading...'); $.ajax({ url: "upload.php", // Url to which the request is send type: "POST", // Type of request to be send, called as method data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values) contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData:false, // To send DOMDocument or non processed data file it is set to false success: function(data) // A function to be called if request succeeds { $(".upload-msg").html(data); } }); } )); |
We are sending image file data by instantiating FormData. The success/failure handlers are triggered based on the result of the upload request.
PHP code
1 2 3 4 5 6 7 8 9 10 | if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_FILES["userImage"]["type"])){ $sourcePath = $_FILES['userImage']['tmp_name']; // Storing source path of the file in a variable $targetPath = "upload/".$_FILES['userImage']['name']; // Target path where file is to be stored if(move_uploaded_file($sourcePath,$targetPath) ){ // Moving Uploaded file echo "file is uploaded successfully"; } else echo "file uploading failed"; } die(); |
It’s a sample code to understand how to save uploaded file to server. Download the zip containing full working code including validation and safely upload image to server, at end of this article.
Preview Uploading Image and validation
If we want to show preview and validate the image being uploaded before submit. Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | $("#userImage").change(function() { $(".upload-msg").empty(); var file = this.files[0]; var imagefile = file.type; var imageTypes= ["image/jpeg","image/png","image/jpg"]; if(imageTypes.indexOf(imagefile) == -1) { $(".upload-msg").html("<span class="msg-error">Please Select A valid Image File</span> Only jpeg, jpg and png Images type allowed"); return false; } else { var reader = new FileReader(); reader.onload = function(e){ $(".img-preview").html('<img src="' + e.target.result + '" alt="" />'); }; reader.readAsDataURL(this.files[0]); } }); }); |
Above given code is written in short manner so that AJAX file uploading process would be understandable easily with little bit knowledge of jQuery, AJAX, HTML5 and PHP.
Hi Uri, i have tried these code for my website and it has worked for me. In case the problem persists, download a working demo for the same code here
hello im kind of new to jquery and ajax technologies. Im trying to incorporate your code into a project that im working on. Your code does not upload an image. It show’s the preview of the picture that i select for upload, but it fails to actually upload the picture to my server, the code stops at the “Loading…” part of the code. The code is simple so im kind of lost… should i rewrite the upload.php file?
And i cant figure out what does the script actually do with the picture that i have uploaded.
Please help! Anybody
Hi Uri
I’m sorry to hear about your concern and want to give you a few tips. First of all ensure that url: “upload.php” in $.ajax({ should be the as same as the name of your php script at server. Second you can use print_r($_FILES) to check are you getting data by ajax and last, the folder where you want to save uploaded photos should exist.
Still if you are unsure and unable to resolve, you can write us at support@fellowtuts.com
Thank you for the reply, i solved the problem. Thx
Best regards!
Hi Uri, i have tried these code for my website and it has worked for me. In case the problem persists, download a working demo for the same code here
No working demo??? zZzz.
Thanks for getting it in our notice. We have done the required changes in demo. Now it’s working.
Please post image uploader with image link generater just like postimage
A bit knowledge of php and jQuery AJAX is enough for that. Isn’t it?
請問我能夠跟您要一份檔案嗎
您的檔案似乎無法下載
最近正在學習 File API 和 MySQL 、AJAX 中 出現了一些問題
您的程式介紹寫得非常簡單,但我還是不太了解
謝謝您!
Sorry , but i can’t download your files in
can you upload a new file or send a email to me ?
thanks a lot!
Oops, sorry! I have edited the download link. Please download now.
Thanks