INTRODUCTION
MODERN UPLOAD
Welcome to a tutorial on how to handle Ajax image upload in PHP. The stone age of the Internet is long over, and gone are the days where we have to reload the entire page to submit a form. If you are trying to attach an image with an upload form, submit without refreshing the entire page – Yes, it can be done. This guide will walk you through how to do it, step-by-step. Read on to find out!
I have included a zip file with all the example source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
CONFESSION
AN HONEST DISCLOSURE
Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!
NAVIGATION
TABLE OF CONTENTS
Step 1 | Step 2 | Step 3 |
Extra | Extra | Closing |
STEP 1
HTML UPLOAD FORM
First, let us start by creating the HTML file upload form.
THE HTML
AJAX Image Upload Demo
No nasty surprises here, this is just a regular Joe HTML form.
- If you want to use the jQuery version, just remove the vanilla script in the
section, and uncomment the jQuery version.
- Change the
accept
attribute of thetag to set your accepted image file types.
- Please feel free to append more
fields to the form as required in your own project.
THE CSS
#upform {
font-family: arial, sans-serif;
max-width: 320px;
padding: 20px;
background: #f2f2f2;
border: 2px solid #ccc;
}
#upform h1 {
margin: 0;
padding: 0;
}
#upform label, #upform input {
display: block;
width: 100%;
box-sizing: border-box;
}
#upform label, #upform input[type=submit] {
margin-top: 10px;
}
#upform label {
font-size: 0.9em;
color: #555;
}
#upform input[type=submit] {
background: #3961a3;
color: #fff;
border: 0;
padding: 5px;
}
Nothing special here as well, just some CSS cosmetics. Feel free to change this to fit your own project’s theme.
STEP 2
THE JAVASCRIPT
Moving on, we shall create the Javascript that will handle the AJAX request – We shall walk through 2 different flavors here, in jQuery, and in vanilla Javascript for those who don’t like the loading bloat.
VANILLA JAVASCRIPT VERSION
function ajaxup () {
// (1) GET FORM DATA + SELECTED FILE
// Yes, we can append POST data as well.
var data = new FormData(),
upfile = document.getElementById("upfile").files;
data.append("upfile", upfile[0]);
data.append("uptext", document.getElementById("uptext").value);
// (2) AJAX INIT
var xhr = new XMLHttpRequest();
xhr.open("POST", "4-ajax-upload.php", true);
xhr.onload = function(res){
var response = JSON.parse(this.response);
if (response.status==1) {
// @TODO - OK
alert("OK");
} else {
// @TODO - ERROR
alert(response.message);
}
};
// (3) GO!
xhr.send(data);
return false;
}
Yep, for you guys who are expecting a complicated script – Sorry to disappoint that AJAX in vanilla is really this simple…
- First, we create a
FormData
object, and append all the data we want to send to the server. - Next, we initiate the AJAX
XMLHttpRequest
object, set it toPOST
mode, set the target handling URL, and what to do after the AJAX call is done withonload
. - Remember to complete the
onload
part. - Finally, we set the dogs loose, and do the AJAX magic.
JQUERY VERSION
function ajaxup () {
// (1) GET FORM DATA + SELECTED FILE
// Yes, we can append POST data as well.
var data = new FormData();
data.append("upfile", $('#upfile').prop('files')[0]);
data.append("uptext", $('#uptext').val());
// (2) AJAX
$.ajax({
url : "4-ajax-upload.php",
method : "POST",
dataType : "json",
data : data,
contentType : false,
processData : false,
success : function (res) {
if (res.status) {
// @TODO - OK
alert("OK");
} else {
// @TODO - ERROR
alert(res.message);
}
}
});
return false;
}
The jQuery version is a little bit simpler.
- We create a
FormData
object, and append all the data as usual. - Use the jQuery
ajax
function to do the AJAX call. - Remember to complete the on success or failure part.
STEP 3
PHP UPLOAD HANDLER
The final piece of the puzzle is to create a PHP file that will handle the AJAX upload and respond accordingly.
THE SCRIPT
$pass,
"message" => $pass ? "Upload OK" : $error
]);
?>
THE EXPLANATION
This one may seem a little challenging for the beginners, but if you look through it section-by-section, it really is pretty straightforward:
- We start with some initiation.
$pass
is a flag that will hold if the process has passed or failed, and$error
to hold any error messages. - Then we check if the uploaded file is a legit image file – We don’t depend on HTML to reliably do the checks.
- If the file checks pass, we move it out of the temporary folder, and into a more permanent folder – Remember to set this to your own.
- Finally, we formulate a JSON response (if the upload passed or failed) that will be picked up by the Javascript.
EXTRA
USEFUL BITS
That’s all for this project, and here is a small section on some extras that may be useful to you.
VANILLA OR JQUERY?
The million dollar question – jQuery or Vanilla Javascript, which is better? If your existing project is already using jQuery, then just stick with it. But otherwise, I will recommend using vanilla – There is no way jQuery can beat vanilla in terms of performance, and the difference is jQuery makes these days is really just a few lines of code.
REFERENCES
- jQuery AJAX manual
- Vanilla XMLHttpRequest
- Vanilla FormData API
DRAG-AND-DROP UPLOAD
Need a cooler upload mechanism? Try drag-and-drop:
3 Steps Simple Drag-and-Drop File Upload (PHP, JS, HTML5)
SAVE INTO DATABASE!?
Need to save the image file into the database instead? Here’s how:
3 Steps to Store and Retrieve Images from MySQL Database In PHP
EXTRA
DOWNLOAD
Finally, here is the download link to the source code as promised.
QUICK START
Skipped the entire tutorial? There’s no database nor any “special set up” required. Just download, unzip into your project folder, and start tracing from 1-upload-form.html.
SOURCE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
CLOSING
WHAT’S NEXT?
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
The post 3 Steps Simple PHP AJAX Image Upload – jQuery & Vanilla appeared first on Code Boxx.