We use AJAX whenever we need to communicate with the server, without reloading the page. But this doesn’t function in the case of File Upload. In usual view, uploading files with AJAX is impossible! (FireFox/Mozilla can do this after change a setting in “about:config” – which we cannot guarantee for a lot of users).
When I was searching for any technique to upload file without reloading page, I found a script in www.webtoolkit.info . But it seemed very complex to me. Then I try to simplify their technique and its working great. So I thought why not share the technique with everybody?
First, look at the demo here to see how it works.
OK. Let’s get into the deep. What happens when we submit a form? The form is submitted to the action page and that page loaded in current frame of window. If the “target” attribute of form indicate “_blank” or any frame name of the window, the page loads in a blank window or in the named frame or inner frame. Here we’ll be using the second method.
First, take an inner frame in anywhere of the page. And set the display property of this frame as “none”:
<iframe name="hiddenFrame" id="hiddenFrame"
src="about:blank" style="display:none" >
Now, just set this frame as the target of your uploading form.
<form name="testForm" id="testForm" enctype="multipart/form-data"
action="upload.php" method="post" target="hiddenFrame">
<input type="file" name="name" />
<input type="submit" value="Upload!" />
If we submit this form now, it will submit the file to the target script on the server (can be in php, asp etc.). The script will upload the file and will load the response in the frame “hiddenFrame”. As the frame is not visible, nothing about this loading will be seen by the visitors. Now, as the uploading page displays nothing after uploading your file, the response can be immediate. Although it’s not AJAX, this technique will upload your file without (visually) reloading page.
var resultDiv =
var uploadedImage = document.getElementById(‘UploadedImage’);
uploadedImage.src = resultDiv.innerHTML;
alert("File Uploaded :" + resultDiv.innerHTML);
echo "Your uploaded file is: <div id=’result’>".$_FILES[‘name’][‘name’]." </div>";
echo "<div id=’result’>Sorry! Error occured!</div>";
Well, that’s it. This technique has already saved my ass once, see if it can save yours also when you need.