How to pass input value to ajax using FormData while uploading images?

I am trying to upload images using ajax and php and I have managed to make it work to a certain level successfully, but I can’t make my input’s value (ID) pass to my php file.

Here’s my scenario.

HTML

<form enctype="multipart/form-data" id="myform">
        <input type="file" name="images[]" multiple id="image"/>
</form>

Button

<button type="button" id="uploadimages" name="thing_id" value="<?php echo $row['thing_id']; ?>" class="btn btn-primary">Save changes</button>

AJAX

$("#uploadimages").click(function () {
        var form = new FormData($('#myform')[0]);

        // Make the ajax call
        $.ajax({
            url: 'uploadimages.php',
            type: 'POST',
            xhr: function () {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', progress, false);
                }
                return myXhr;
            },
            //add beforesend handler to validate or something
            //beforeSend: functionname,
            success: function (res) {
                $('#content_here_please').html(res);
                /**/
            },
            //add error handler for when a error occurs if you want!
            //error: errorfunction,
            data: form,
            cache: false,
            contentType: false,
            processData: false
        });
    });

PHP

$thing_id = $_POST['thing_id']; // I get undefined error, I should have gotten $row['thing_id'] value, like 3 or 5.

The way your script is setup, <button> must be in the form OR try this:

$("#uploadimages").click(function () {
    var form = new FormData($('#myform')[0]);
    form['thing_id'] = $(this).val()

I managed to make it work by adding my button into my form, but thank you. I learned something new here.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.