Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery + php file upload. Pass multiple parameters

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>
like image 600
luiquao Avatar asked Nov 01 '22 11:11

luiquao


1 Answers

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;
    });
});
like image 103
Adam Merrifield Avatar answered Nov 09 '22 13:11

Adam Merrifield