Ajax File Upload Made Easy

ajax_upload_featured

I am sure that many of you have searched for Ajax file upload for long time and all you could find was some plugins that is difficult to customize and sometimes even understand. The problem is that there is no Ajax support for file upload. There was no chance on earth you could send a file using an XMLHttpRequest. So some workarounds have been introduced and the most famous one was introduced by Google which suggested the use of a hidden iframe.

Today, I will show how you can upload a file using a hidden iframe. View Demo

In this tutorial we will be uploading image files. However this method is valid for all file types.

Ok now, enough with this and let’s get down to business.

In order to do this, we need to have three things:

  1. HTML form and a hidden iframe to submit the file
  2. PHP to handle the actual file upload
  3. jQuery to retrieve the data posted by PHP to the iframe

The upload process will go in the following order, first the form will be submitted and the file will get uploaded, then the PHP will echo the file name back to the hidden iframe before the jQuery retrieves the file name to be later displayed on the page. The jQuery will also be used to show a nice loading sign to the user during the file upload process.

Here how your code will look like, first the HTML form:

<div id="upload_wrapper">
<form id="upload" action="index.php" method="post" name="upload" enctype="multipart/form-data" target="upload_target"><input id="uploaded_file" type="file" name="uploaded_file" size="30" />
<input id="sent" type="submit" name="sent" value="Upload" />
</form>
</div>

The hidden iframe:

<iframe id="upload_target" name="upload_target" style="display: none; height: 10px; width: 10px;"></iframe>

The PHP code that handles the actual file upload:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

// Access the $_FILES global variable for this specific file being uploaded
// and create local PHP variables from the $_FILES array of information
$fileName = $_FILES["uploaded_file"]["name"]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder

// Place it into your "uploads" folder mow using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName");
// Check to make sure the move result is true before continuing
if ($moveResult == true) {
   echo"<div id='filename'>$fileName</div>";
   }
}

Finally the jQuery code that will do the magic:

//if submit button is clicked
$('form#upload').submit(function(){  

  $('#upload_wrapper').hide();
  $('#loading').show();

  // get the uploaded file name from the hidden iframe
  $('#upload_target').unbind().load( function(){
  var img = $('#upload_target').contents().find('#filename').html();

  $('#loading').hide();

  // load to preview image
  if (img){
  $('#preview').show();
  $('#preview').attr('src', 'uploads/'+img);
  $('#image_wrapper').show();
  }

  });
 });
});

In the form tag notice how the target attribute is set to the name of the hidden iframe forcing it to submit to the iframe. After the form is submitted the PHP handles the file upload and then echos the file name to a div with a known id  to be later retrieved by the jQuery. Line 9 of the jquery code shown above does this. Later in line 14 the file name is appended to the src attribue of the HTML img tag.

DemoDownload

Download the source code for fully working example.
I hope this was helpful. If you like it please do not forget to share, +1, tweet etc.

Ajax File Upload Made Easy
6 votes, 4.33 avg. rating (85% score)
  • Posted in: JavaScript & jQuery
Husamaldin Tayeh

Posted by

Husamaldin is a computer programmer, blogger, entrepreneur and an overall thinker. He is the founder and editor of Coders Mount. He loves everything about computers and programming. Find out more about him here or follow him on Twitter Google+ | LinkedIn.

  • Hakan Bilgin

    Thank you for share this usefull information friend :)

    Hakan

    • Husamaldin Tayeh

      You are welcome Hakan

  • Esam

    nice website .. congratz

    • Husamaldin Tayeh

      Thanks Esam

  • David

    This is sick dude, keep the nice work up !

  • Robert

    Husamaldin … you do not know how many hours I have spent behind the PC trying to figure out how to do this … thank you very much, I wish to see more of this nice and extraordinary work.

    • James

      Yeah man, I agree with you.It’s really made easy, specially getting the name from the hidden iframe.
      I wanna say thanks Husamaldin, nice job.

  • http://twitter.com/archeristic Aiko Katherine Olaer

    Just a question. After I clicked the button, I see the picture. Yet when I try to see the pictures in the uploads folder, why does it become an invalid image file? Is it just temporary?

    • http://www.codersmount.com/ Husamaldin Tayeh

      Hi Aiko,
      Are you uploading to web server or local folder?
      You need to make sure that the upload folder is writable. You can do that by changing the folder read/write permissions. And if you are uploading to a web server then you can do that by write clicking the folder and setting the CHMOD to 777 or 755

      Please let me know if this was helpful.

    • http://twitter.com/archeristic Aiko Katherine Olaer

      i’m trying to upload locally. But good point with the folder permissions. I forgot that bit. I’ll check it out. I’ll be sure to tell you whatever output I got. Thank you. 😀

    • http://twitter.com/archeristic Aiko Katherine Olaer

      It’s working fine. I did some tweaks. This really helps me, esp with adding image preview to my site. Thank you so much! =) And of course, I acknowledged your work.

    • http://www.codersmount.com/ Husamaldin Tayeh

      That’s great, Glad you found it helpful :)

  • http://twitter.com/archeristic Aiko Katherine Olaer

    And thank you, by the way for this really really helpful post for newbies like me. 😀 Good job!

  • Anand

    Its Really Super :) Thanks

    • http://www.codersmount.com/ Husamaldin Tayeh

      You are welcome :)

  • toni amengual

    Great stuff, nicely done. I figured out I couldn’t build an image uploader with AJAX until I found this post. The explanation is clear and brilliant. Congrats.

    • afsdf

      asdf dsasdf got it????

    • afsdf

      woww

    • afsdf

      nested

  • victor sotto

    where’s the ‘demo’ and the download?

    • http://www.codersmount.com/ Husamaldin Tayeh

      I have recently transferred the site to a new host and I forgot to upload the demos and downloads folder. I have fixed this. The demos and downloads are available now.

    • victor sotto

      thank you! but how do i make this script support multiple upload? could you please give us example how to repopulate and edit/delete files that is/are already uploaded? i wish you have a Codeigniter for this with the following features i mentioned. :) newbie here. thanks again for you response…

  • Guest

    i want use change function instead of submit. i click function used but i can’t add my form’s inside again form. sorry my english language