ajax file upload

ajax file upload

 
<html>
  <head>
    <title> file upload script in ajax </title>
    <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
  </head>
  <body>
    <form name="comp_logo" id="comp_logo" method="POST" action="" enctype="multipart/form-data">
      <input type="file" name="add_logo" id="upload_file" class="add_logo">
      <input type="button" class="upload_logo" value="upload"><br>
    </form>
    <div>
        you must add a file upload script in http://example.com/admin/admin-ajax.php php :<a href="http://www.w3schools.com/php/php_file_upload.asp"> upload script </a>
    </div>
    <script type="text/javascript">
      jQuery(document).ready(function(){
        jQuery('.upload_logo').click(function(){
          var fd = new FormData(); // form data object
          fd.append( 'file', jQuery( '#upload_file' )[0].files[0] ); // add the file to the form data
          fd.append( 'action', 'obs_update_comp_logo'); // add the extra paramater to the form data object

          // Ajax call
          jQuery.ajax({
            data: fd, // data send with file
            processData: false,
            contentType: false,
            type: 'POST',
            async: false,
            url:'http://example.com/admin/admin-ajax.php',
            success: function(res){
                alert("file uploaded !!!")
                 /* sucess function */
            }
          });
          return false; // to stop the process
        });
     });
    </script>
  </body>
</html>

Leave a comment