Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax post file field

Tags:

jquery

ajax

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

like image 275
geoffs3310 Avatar asked Apr 19 '11 15:04

geoffs3310


People also ask

Can we upload file using AJAX?

File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .


2 Answers

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

like image 157
austinbv Avatar answered Nov 05 '22 04:11

austinbv


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.

like image 27
WhiteHorse Avatar answered Nov 05 '22 06:11

WhiteHorse