geoffs3310
geoffs3310

Reputation: 14008

jQuery ajax post file field

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

Upvotes: 18

Views: 120536

Answers (4)

WhiteHorse
WhiteHorse

Reputation: 716

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.

Upvotes: 12

Herik Modi
Herik Modi

Reputation: 7

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.

Upvotes: -3

Dutchie432
Dutchie432

Reputation: 29160

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

Upvotes: -4

austinbv
austinbv

Reputation: 9491

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

Upvotes: 18

Related Questions