简体   繁体   中英

Submitting a form with a file using JQuery and AJAX

I have a form, with a file input, that submits just fine when I use the default action to submit the form. But, when I use JQuery and AJAX to make the call to the PHP file, it does not seem to get the file. Is there something that I need to add for sending files through JQUERY/AJAX?

My HTML:

<form id="photo-form" enctype="multipart/form-data" method="post" action="">
    <input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
    <input type="file" class="upload-input" name="upload-new-input" autocomplete="off"/>
    <input type="submit" name="submit" value="submit/>
</form>

My JQuery:

$(document).ready(function() {
    $("#photo-form").submit(function(e) {

        e.preventDefault();

        var dataString = $(this).serialize();

        $.ajax({  
             type: "POST",  
             url: "uploadcover.php",  
             data: dataString,
             async: false,
             success: function(data) {
                 alert(data);
             }
        }); 

    });
});

You can use FormData to upload file with data

Here is sample code

JQuery

$("#photo-form").submit(function(e) {
        e.preventDefault();
        var formData = new FormData($(this)[0]);

        $.ajax({  
             type: "POST",  
             url: "uploadcover.php",  
             data: formData,
             async: false,
             cache: false,
             contentType: false,
             processData: false,
             success: function(data) {
                 alert(data);
             }
        }); 
        return false;
})

You can get it on PHP

PHP CODE

$Img = $_FILES['upload-new-input'];

You can see tutorial Uploading files with jquery ajax

Hope It helps you :)

You cannot access file directly.

You can use a plugin, to do this for you, ie https://github.com/blueimp/jQuery-File-Upload

Also, in html5 it is possible to access a file from file input as a blob. You can than send it using formData.

More info here: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM