AJAX style file upload without page refresh

July 13th, 2009 in PHP, Web UI Programming. 11 comments
1 Star2 Stars3 Stars4 Stars5 Stars (9 votes, average: 4.33 out of 5)
Loading ... Loading ...

Here’s a quick and dirty How-To on creating an AJAX type file upload without refreshing the html page. It is not a very elegant solution but does work well across browsers. Although the server side code shown here uses PHP, this solution can be adapted for Java, Perl or whatever else you use on the server.

  • First the html. We define a form and an iframe target with width and height set to 0 in order to keep it hidden. A message to display the upload status is also defined (within the span tags) and is initially hidden.

    <form id="uploadform" method="post"
    enctype="multipart/form-data"
    action="lib/upload.php">
    
    <input name="file" id="file" size="27" type="file" /><br />
    <input type="submit" name="action" value="Upload" />
    <span id="status" style="display:none">uploading...</span>
    <iframe id="target_iframe" name="target_iframe" src="" style="width:0;height:0;border:0px"></iframe>
    
    </form>
    
  • Next the javascript. Explanation is inline:
  • <script type="text/javascript">
    function initUpload() {
    
       /*set the target of the form to the iframe and display the status
          message on form submit.
      */
    	document.getElementById('uploadform').onsubmit=function() {
    	document.getElementById('uploadform').target = 'target_iframe';
        document.getElementById('status').style.display="block"; 
    
    	}
    }
    
    //This function will be called when the upload completes.
    function uploadComplete(status){
       //set the status message to that returned by the server
       document.getElementById('status').innerHTML=status;
    }
    
    window.onload=initUpload;
    </script>
    

    So how is uploadComplete called? keep reading….

  • Now for the server side code that handles the file upload (upload.php). We have used a barebones php script that only performs a few checks and copies the file over to a ‘tmp’ directory. Of course, your production code will have to be more robust. But what you need to pay attention to here is the returnStatus function that returns html and javascript for the iframe. Note that the uploadComplete() method of the above javascript is being called in the code snippet returned by this method.
    Also you need not use php for the serverside script, you can substitute php with any other language, as long as your returns the same string (or something equivalent) as that being returned from returnStatus.

    <?php
    
      $file_id='file';
      $status='';
    
      $filename=$_FILES[$file_id]['name'];
      $tmpfile=$_FILES[$file_id]['tmp_name'];
    
      if(!$_FILES[$file_id]['name']) {
        	echo returnStatus("<font color=\'red\'>no file specified</font>");
        	return;
      }
      /*copy file over to tmp directory */
      if(move_uploaded_file($tmpfile, "tmp/".$filename)){
        $status='Success';
      }else{
        $status='<font color=\'red\'>Failed</font>';
      }
      echo returnStatus($status);
    
    function returnStatus($status){
    	return "<html><body><script type='text/javascript'>function init(){if(top.uploadComplete) top.uploadComplete('".$status."');}window.onload=init;
    </script></body></html>";
    
    }
    
    ?>
    
  • Obligatory screenshot:
    Ajax style upload without page refresh

    Ajax style upload without page refresh

Related articles

Create a html table with thin borders
Jump to a different location on the same HTML page on dropdown list selection

Tags: , ,

11 Responses to “AJAX style file upload without page refresh”

  1. El Severo at
    says:

    Correct these mistakes please:
    At HTML [the quotes at style property]

    and Ajax:

    document.getElementById(’uploadform’).onsubmit=function()

    Regards,
    El

  2. admin at
    says:

    Thanks for pointing this out..The two errors have been recitified.

  3. Antonio Santos at
    says:

    Hi…

    I can’t do this example to work (sorry for my bad english)…

    Is there possivel do you the complete files por download??

    Thanks,

    Antonio

  4. admin at
    says:

    Antonio,
    Can you be more specific as to what errors you are getting?
    All the code is already there above. Just cut and paste. Put the html and javascript in one html file and put the php code on your server side (in lib/upload.php). Thats it.

  5. Yungky Leonardi at
    says:

    Hi.
    It always gives me “no files specified” everytime I click on the upload button.

  6. cho at
    says:

    You need to put a valid action atrribute in the form tag.

  7. admin at
    says:

    The action attribute is valid. In this case the php file is put inside the lib directory on the server.

  8. Surya at
    says:

    I Really Worry about how to make file upload to my server which is in .Net from html page without page refresh

  9. Justin at
    says:

    It works great! Thanks so much

  10. James at
    says:

    I can’t get it to work either. The main window is still the target of the form’s action.
    I tried this using IE and Chrome on windows 7.

  11. bettisfr at
    says:

    Many many thanks for your example :-)
    This code works a lot!!!

Leave a Reply

Sponsors