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
File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With