luiquao
luiquao

Reputation: 1114

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>

Upvotes: 5

Views: 3403

Answers (3)

Adam Merrifield
Adam Merrifield

Reputation: 10407

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;
    });
});

Upvotes: 2

Oki Erie Rinaldi
Oki Erie Rinaldi

Reputation: 1863

Try to define a new bariable

var name = "hello";

and then insert it into $.ajax data

    $.ajax({
        url: 'post.php',
        type: 'POST',
        data: "form_data="+form_data+"&name="+name,
        success: function (data) {

            $('#result').html(data); 

        },
        contentType: false,
        processData: false
    });

I never test this script, but there's no matter to check it out :D

Upvotes: 0

paquino
paquino

Reputation: 464

I would JSON.stringify it then json_decode when you get it back in PHP

var data = JSON.stringify({ /* object */ });

Then in your php $data = json_decode(....);

Upvotes: 0

Related Questions