Zakukashi
Zakukashi

Reputation: 586

Jquery file posting help needed

Im trying to upload a file using jQuery. I use a hidden form which contains an Input, then I use jQuery to trigger the file browser. Once the input is changed the file is then posted to the PHP server script.

My problem is that if I just do $("form1").submit(); everything works perfect but my page then gets redirected. To avoid redirecting I want to get the response text from the PHP script therefore I used the jQuery Post function but this time the PHP script doesn't recognize that there is a file post and returns an error whenever theres ($_FILES) = nothing.

My HTML Code:

<form id="form1" name="up1" method="POST" action="upload.php" enctype="multipart/form-data">
 <input style="width:0px;height:0px"id="br" type="file" name="Filedata"/>
 </form>

jQuery:

 $("#br").change(function() {
   var $el = $('#br');
  $('#form1').submit(); 
});
//The code above works perfectly if I dont add this code below.
 $("#form1").submit(function(event) {
 event.preventDefault();
 var $el = $('#br');
 var $form = $( this ),
 term = $form.find('input[name="Filedata"]').val(),
 url = $form.attr( 'action' ),
 enctype= "multipart/form-data";

$.post( url, { s: term },
  function( data ) {
     alert(data);
   }
  );
 });

Upvotes: 1

Views: 174

Answers (2)

Gormit
Gormit

Reputation: 101

Instead of write it by yourself, you can try ajax-upload plugin.

Upvotes: 0

Timo
Timo

Reputation: 935

Its impossible to upload files with Ajax. However, there's a trick: Create a hidden iframe and set the Form's target to the iframe. Use the iframe's readyState property, to tell when the fileupload has completed. Its not real Ajax, but looks just like it.

Upvotes: 1

Related Questions