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
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.
Source: Stackoverflow.com