简体   繁体   中英

How to upload by ajax post serialize

I have form upload:

 <form method="post" id="edit_form" onsubmit="return edit(this.id);" enctype="multipart/form-data">
    <input type="file" name="thumb" />
    <input type="submit" value="Upload" />
</form>

and javascript function:

function edit(id){
    httplocal = location.href;
    var jqxhr = $.post(httplocal,$("#"+id).serialize(), function(data) {
        if(data.status == 1){
            $("#success").show();
        }else {
            $("#error").show();
        }
    }, "json")
    return false;
}

in php i check :

if ($_FILES['thumb']['error'] != UPLOAD_ERR_NO_FILE) {
    code upload here...
}

but form is empty $_FILES['thumb'] is null . Sorry my english.

You don't need to serialize the form. Instead you should send an instance of the FormData class.

        $("form").submit(function(event) {
            event.preventDefault();

            var data = new FormData($(this)[0]);

            $.ajax({
                // Note: to access both $_POST and $_FILES you should set these to false
                processData : false,
                contentType : false,

                url : "/php-script.php",
                data : data,
                success : function(response){
                    console.log(response);
                }
            });
        });

That's a very common technique to send files via AJAX using jquery.

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