Ajax file upload PHP / jQuery Tutorial

The asynchronous file upload, using some XMLHttpRequest (Ajax), is technically not possible. Most JavaScript examples and tutorials call this method still Ajax upload and the image or file is uploaded by using a “virtual IFRAME”. Anyway it’s still user friendly way to provide an upload function for your visitors or users.

In this quick tutorial I will show your how-to create such an Ajax image upload form using the jQuery Form plug-in and my PHP upload class. There is also an Ajax upload demo page which will show how it really works.

The scripts are very simple, build your image upload form just like normal. In place of posting the form data to a PHP script, you will use some JavaScript code to post the data to a PHP script in the background.

Requirements

Ajax file upload PHP tutorial code

Download the required files and place the JavaScript files into the same directory as your HTML document and place the following JavaScript code into the HTML header:

Next create a PHP script named “upload4jquery.php” and place it in the same directory where the other files are located. Place this code into your PHP file:

This tutorial or guide is not about how to use the PHP upload class. If you never used the class before, than try the example files first and try than the Ajax upload form.

Paths and upload directories

You need to create two upload directories: One for the upload main file and one for the thumbnails. Check/change the permission for the directories (CHMOD the directories with 0755). If you use the same structure as suggested in the PHP class file, there is no need to change the includes at the top of the PHP script.

Now we need to create the form HTML and some other containers where the response data will be placed.

The file loading.gif is the upload indicator image, pick the file I’ve used on the demo page or check Google for other stylish images or use an online image generator.

Some final note, the code works as it is. Don’t change variable names or form field attributes, if you’re not sure how to change them inside your JavaScript code.

This (older) Ajax file upload PHP tutorial was posted at finalwebsites.com previously, I updated the code and I think this blog is a much better place. 

Comment Rules

Don’t post your code here, post your code block or snippet to pastebin and include the pastebin URL in your comment.

I delete all comments with non related links inside the comment text. Don't use keywords for the field of your real name (most people like to use your name for their answer). Keep your comment related to the topic, if your question is off-topic, please use the contact form instead.

Leave a Reply

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

*
*
Website