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);
}
);
});