0

I have studied a lot of answers in stackOverflow but haven't figured out the simplest way of uploading an image from a form. I am trying to figure out a way to upload an image using Ajax. Although the form, PHP and Ajax coding is huge, I am giving you the important parts. When I click the submit button, error message is shown, viz undefined index.

HTML

<form method="post" enctype="multipart/form-data">
<tr>
    <th>Image</th>
    <td><input type="file" name="image" id="img"></td>
  </tr>
</form>

Ajax

$(document).on('click','#sub_prod',function(event){
        event.preventDefault();
        $.ajax({
            url:"product_add_back.php",
            method:"post",
            data:$('form').serialize(),
            dataType:"html",
            success:function(strMsg){
                    $("#prod_add").html(strMsg).show().fadeOut(3000);

                }

            })

})

PHP

$image_name=$_FILES["image"]["name"];
echo $image_name;
die();
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Don'tDownvoteMe
  • 501
  • 2
  • 16

1 Answers1

1

$().serialize() will not include $_FILES content, so you need to use FormData object

$(document).on('click','#sub_prod',function(event){
    event.preventDefault();
    var formdata = new FormData($('form')[0]);

    $.ajax({
        url: "product_add_back.php",
        method: "post",

        data: formData,
        processData: false,
        contentType: false,

        success: function(strMsg){}
    });
});

Please note that you pass 3 params: data: formData, processData: false and contentType: false

Justinas
  • 41,402
  • 5
  • 66
  • 96
  • 1
    I can understand that `FormData` constructor is supplied with `form` and it creates and object as mentioned in the documentation but why do we use `[0]` along with it? I tried removing it and no data was submitted into the database(errors thrown). Would you please tell me why do we use `[0]`? – Don'tDownvoteMe Mar 01 '18 at 09:07
  • 1
    @Don'tDownvoteMe `$('form')` will return jQuery object that is not good for FormData parser. You need actual DOM element and it's located in `0` index of `$('form')`, so `$('form')[0]` gets you actual DOM element instead of jQuery wrapper – Justinas Mar 01 '18 at 12:01
  • Which DOM element do we target using `$('form')[0]`? – Don'tDownvoteMe Mar 01 '18 at 12:26
  • 1
    @Don'tDownvoteMe The one that you select in query - `
    `
    – Justinas Mar 01 '18 at 12:30