0

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.

Ram Sharma
  • 8,676
  • 7
  • 43
  • 56
Dũng IT
  • 2,751
  • 30
  • 29

1 Answers1

2

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.

Yang
  • 8,580
  • 8
  • 33
  • 58