I have a form with a file input. How do I get the file and post it to a php script using jQuery? Can I just use .val() to get the value and then post this? For example say the file input has an id of file could i just do:
$('#submit').click(function() {
var file = $('#file').val();
$.post('script.php', { "file": file }, function(data) {
// do something here after post complete
}, 'json');
})开发者_运维百科;
Thanks
This should help. How can I upload files asynchronously?
As the post suggest I recommend a plugin located here http://malsup.com/jquery/form/#code-samples
I tried this code to accept files using Ajax and on submit file gets store using my php file. Code modified slightly to work. (Uploaded Files: PDF,JPG)
function verify1() {
jQuery.ajax({
type: 'POST',
url:"functions.php",
data: new FormData($("#infoForm1")[0]),
processData: false,
contentType: false,
success: function(returnval) {
$("#show1").html(returnval);
$('#show1').show();
}
});
}
Just print the file details and check. You will get Output. If error let me know.
Try this...
<script type="text/javascript">
$("#form_oferta").submit(function(event)
{
var myData = $( form ).serialize();
$.ajax({
type: "POST",
contentType:attr( "enctype", "multipart/form-data" ),
url: " URL Goes Here ",
data: myData,
success: function( data )
{
alert( data );
}
});
return false;
});
</script>
Here the contentType
is specified as multipart/form-data
as we do in the form tag, this will work to upload simple file
On server side you just need to write simple file upload code to handle this request with echoing message you want to show to user as a response.
File uploads can not be done this way, no matter how you break it down. If you want to do an ajax/async upload, I would suggest looking into something like Uploadify, or Valums
精彩评论