How to pass extra variables through $.ajax to post.php?
My first variable is
var form_data = new FormData($(this)[0])
I can pass it alone, but if I want to add another variable and make an array
data {
    "form_data": form_data,
    "name": "hello"
}
it does't work.
My current code:
$(document).ready(function() { 
    $("form#data").submit(function(){
        var form_data = new FormData($(this)[0]);
        $.ajax({
            url: 'post.php',
            type: 'POST',
            data: form_data,
            success: function (data) {
                $('#result').html(data); 
            },
            contentType: false,
            processData: false
        });
        return false;
    });
});
<div id="result"></div>
<form id="data" method="post" enctype="multipart/form-data">
    <input name="file" type="file" />
    <button>Submit</button>
</form>
                Try this. The formData object has a method append. We're going to use that instead. We're going to append the file under the name file. In PHP access it with $_FILES['file']. Now for the array or object that you want to add to it. Use JSON.stringify on it to turn it into a string. We append the JSON string and add it to the name 'object'. To access the JSON in PHP json_decode($_POST['object']) will turn it into an object.
Fiddle
$(function(){
    $("form#data").submit(function (e) {
        e.preventDefault();
        var form_data = new FormData(),
            o = {};
        o.name = 'Adam';
        o.arr = ['test', 213];
        form_data.append('file', $('input[name="file"]', this)[0].files[0]);
        form_data.append('object', JSON.stringify(o));
        $.ajax({
            url: '/info/',
            type: 'POST',
            data: form_data,
            success: function (data) {
                $('#result').html(data);
            },
            contentType: false,
            processData: false
        });
        return false;
    });
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With