Ajax File Upload Tutorial

In this article you will see how to upload file using JavaScript, iFrame so that it looks like uploading file using Ajax. As we know that to create a pure Ajax file upload system is not possible because of security limitations of JavaScript. All of the Ajax upload systems use some third party tools for the AJAX feeling.

The concept:

Create a simple HTML form to browse file

Set the target to an iFrame which is on an actual page but hidden

Call a JavaScript function on submit form to display the animation

Hide the animation when PHP part finishes the upload process

The HTML file we will use in this article is quite simple. It just have a simple form with a file field and a submit button. However don’t forget about the enctype parameter in the <form> HTML tag. Use the below code to create the form:

Above HTML and CSS code will generate an HTML form exactly like below screen shot:

Now we need two blocks where we will display the progress animation and in another block we will inform the user whether the upload was success or not. By default the progress animation block content is hidden. Just add the below code immediately before the <label> tag in the <form> tag –

Above HTML includes an image. Please collect the image from the script that I have attached at the bottom of this article.
Now we will add a hidden iFrame to the page which is used as the form target. See the code below:

Now We need to write a JavaScript function which makes this block visible if the submit button was pressed. It is a very simple code that only changes the visibility parameter. Check the below Javascript Code:

Let’s add another JavaScript function that will call at the end of the upload process. This code will be print out a result message depending on its parameter and hides the progress block again. See the below JavaScript Script:

The $target_path variable store the directory path to upload any file. The DIRECTORY_SEPARATOR is a pre-defined PHP constant. The move_uploaded_file() function checks to ensure that the file designated by the first parameter is a valid upload file. If the file is valid, it will be moved the file given by the second parameter. The sleep() command is used to make animation a bit longer in case of very fast uploads. As we know the iFrame is not visible, however we can call a JavaScript function here. And exactly this is the point where we called the JavaScript function defined in the HTML code to hide the progress animation and display the file upload result on the main page.