AJAX-Like File Uploads with jQuery
- AJAX-Like File Uploads with jQuery
- Setting Up the PHP Script
- Creating the HTML Form
- Building the jQuery Script
- Wrapping Up
“Due to security restrictions you will not be able…”
I hate when a sentence begins with those words, but in your everyday work as a web developer, you are likely to hear them spoken again and again. When AJAX started becoming popular, web developers rejoiced because they could build rich interactions with servers. These interactions could occur without reloading web pages-right up until they wanted to build a file upload widget and ran head long into the sentence above.
It makes sense that these restrictions are in place. It would be very easy for web developers to exploit JavaScript hacks to invade and abuse file systems on both user systems and servers. So how can you build a file upload widget that appears to act just as an AJAX interaction would?
You use an HTML iframe element!
Here’s what you will need:
- The jQuery library: http://jquery.com
- A text editor
A local web server (for testing)
For Mac, you can use MAMP.
For PC, you can use XAMPP.
- Downloadable code (jquery_file_upload.zip)
Let’s Get to Work
For this tutorial, you will create three files: the HTML file to display the upload form, a PHP (please feel free to use any scripting language that you are comfortable with) script to handle the actual file upload, and a jQuery script to perform all of the necessary actions to make the upload appear to happen as if it were an AJAX process.
Figure 1 illustrates the directory layout for our project. Make sure to create a folder for the uploads in the same directory where the files created for this project will be stored. Save the jQuery library file to this folder as well.
Figure 1 Directory layout for this project.