Home > Jquery, LAMP, Web Development > Ajax File Upload without iframe

Ajax File Upload without iframe

The Invisible I-frame File Upload method works in almost all browsers.

This post explains using FormData to submit forms that is supported by most new browsers.

<?
if( isset($_POST) && ! empty($_POST) ) {
 
     $file = $_FILES['myfile'];
 
     $output ="Response From the Server\n";
     $output .= "myInput = ".$_POST['myInput'];
     $output .= "\n".'File Name: '.$file['name'];
     $output .= "\n".'File Type: '.$file['type'];
     $output .= "\n".'File Size: '.$file['size'];
     $output .= "\n".'File Tmp Name: '.$file['tmp_name'];
 
     echo $output;
     exit;
}
?>

<html>
<head>
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
     <script type="text/javascript">
         jQuery(document).ready(function($){

         /**
          * when the file is selected 
          */ 
          $("#myfile").change(function() {

               var file = $('#myfile')[0].files[0];

               // new form data 
               var formData = new FormData();
               formData.append('myfile', file); // add the file details
               formData.append('myInput', "Hello World"); // add other data as required
 
               // make an ajax post request 
               $.ajax({
                   url: '/test/file.php',
                   type: 'POST',
                   data: formData,
                   processData: false, // this has to be set to false
                   contentType: false, // this has to be set to false
                   error: function(jqXHR, textStatus, errorThrown){
                       alert("Failed"); 
                   },
                   success: function(data) {
                       alert(data);
                   }
              });
         });
     });
 
 </script>
</head>
<body>
    <input type="file" name="myfile" id="myfile">
</body>
</html>
Categories: Jquery, LAMP, Web Development
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: