nav-left cat-right
cat-right

Ajax-like Unobtrusive File Upload

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" >
    </iframe> 

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!" />
    </form>

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.

What more?

For many purpose, we might need a callback function when using AJAX. For this file uploading technique also, we will try to create something like that. First, we’ll write the callback function as a simple JavaScript function in the header of the uploading page:

<script language="javascript">
function trackThis()
{
var resultDiv = 
    window.frames.hiddenFrame.document.getElementById(‘result’);
var uploadedImage = document.getElementById(‘UploadedImage’);

uploadedImage.src = resultDiv.innerHTML; 
uploadedImage.style.display="block";

alert("File Uploaded :" + resultDiv.innerHTML);
}
</script>

When the uploading of the server page is complete, it should print the JavaScript code in the hidden iframe, to call the callback function with the reference “window.top”. Any other required information also can be printed in specific DIVs. It will enable us to retrieve any response information using the innerHTML of any specific DIV (as shown in example callback function).

Example:

<?php
print_r($_FILES["name"]);
if(move_uploaded_file($_FILES["name"]["tmp_name"], 
            dirname(__FILE__)."/".$_FILES['name']['name']))
{
echo "Your uploaded file is: <div id=’result’>".$_FILES['name']['name']." </div>";
}           
else
{
    echo "<div id=’result’>Sorry! Error occured!</div>";  
}
echo <<<test
<script type="text/javascript">
window.top.trackThis()
</script>
test;
?>

Well, that’s it. This technique has already saved my ass once, see if it can save yours also when you need.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • Wists
  • Furl
  • Ma.gnolia
  • NewsVine
  • Reddit
  • Simpy
  • StumbleUpon
  • Technorati


18 Responses to “Ajax-like Unobtrusive File Upload”

  1. Cool. This is heading to be a resourceful blog – where I might come to see if any of my problems being solved once.

    Great job anis bhai! Keep this blogging spirit up and soon the world will recognize your potential.

    Cheers

  2. Tarek BANGLADESH says:

    Wao!!!!!!
    it’s a great work. Well done anis bhai.. Keep it up.

  3. dosto says:

    its not excellent
    it not very good
    it not good
    it is very bed

    Because I don’t know php, so i cant understand it.
    But i think it will super duper for them, who will understand it.

  4. Valentica BANGLADESH says:

    It’s really helpful. Thanks to u for this article and wants more …

    Thanks

    Valentica

  5. hasin BANGLADESH says:

    mm hmm – great article.

    did u check swfUpload object?

  6. Jahed BANGLADESH says:

    Anis vai,

    I’ve tried to use this technique in code igniter but failed.
    Would u plz help me?

    Thanks!

  7. anisniit BANGLADESH says:

    @Jahed
    Sure.
    Mr. Kabir of Right Brain Solution Ltd. already working with this technique successfully in codeigniter. You can contact with him or send me your code how u have tried. I will try to solve it.

    Thanx
    Anis uddin Ahmad

  8. Jahed BANGLADESH says:

    Oh !

    You r realy a boss of the bosses. This article realy helped me. I’ve used it in code igniter and it works well.

    Go On ….

    Thanks!

  9. RaJu HONG KONG says:

    great work bondhu !!!!!!!!!!

  10. real bondhu………………..

  11. Humayun Kabir UNITED STATES says:

    Great job! This article help me a lot. I’m facing problems to upload images and submit forms using ajax. This article help me to solve the problem. I have successfully implement this technique to our internal framework which is by our company.

    Thankx again,
    Humayun Kabir
    Sr. Web Developer
    United Group International (UGIBD)
    http://www.ugibd.net

  12. Thanks Man!!!.
    You saved another’s time!

  13. nhanthanh VIET NAM says:

    upload error

  14. nhanthanh VIET NAM says:

    thu lai nhe

  15. Ralph Ames GREECE says:

    The demo at the top fails to load.

  16. [...] only lhave a few ways to upload files without reloading the whole page. You can do this by using an iframe, flash or through a java applet. Since applets support drag and drop, we can use it to create a [...]

  17. Hello,thanks for this wonderful blogg, i really find many new things on it and i really loved the design of the blogg. I found it on yahoo. I also want to wish you a happy new year.

  18. Anis Ahmad HONG KONG says:

    @Lorenzo Ozenne
    Thanks and Happy New Year :)

Leave a Reply