How to pass attached object without losing array structure

Asked

Viewed 29 times

0

How do I attach an array, via jQuery/AJAX, and continue to receive data in a PHP page in the following structure:

Array
(
    [cadeia-suprimento] => Produto final
    [produto] => 2
    [categoria] => 4
    [subcategoria] => 15
    [descricao] => Alasca
    [medida] => M
    [supMaxima] => 
    [comunicacaoMotor] => 1
    [acabamento] => 3
    [dimensao] => 19MM
    [codigo] => PN-0001
    [preco-custo] => 175,00
    [preco-venda] => 
    [composicao] => Array
        (
            [0] => 1
        )

    [percentComp] => Array
        (
            [0] => 
        )

)

jQuery:

jQuery.ajax({
    url: "actions/cadastrar-material.php",
    type: 'post',
    enctype: 'multipart/form-data',
    data: $('#formCadMaterial, #formComposicao').serialize(),
    success: function(data){
    }
});

I need to pass attached to this data the following object:

JSON.stringify(checkedItems), where checkedItems is an array checkedItems = {};

Obs.: tried to use new FormData() and append, unsuccessful.

1 answer

0

jQuery:

var formCad = $('#formCadMaterial').serialize();
var formComp = $('#formComposicao').serialize();
var data = new FormData();

data.append('formCad', formCad);
data.append('formComp', formComp);
data.append('modSelecionados', JSON.stringify(checkedItems));

jQuery.ajax({
    url: "actions/cadastrar-material.php",
    type: 'post',
    enctype: 'multipart/form-data',
    contentType: false,
    processData: false,
    data: data,
    success: function(data){
    }
});

PHP:

parse_str($_POST['formCad'], $formCad);
parse_str($_POST['formComp'], $formComp);

foreach(json_decode($_POST['modSelecionados']) as $key =>  $value){
    //echo "\n".$key."→".$value;
}

$cadeia_suprimento  = $formCad['cadeia-suprimento'];
$produto            = $formCad['produto'];
$composicao         = array_combine($formComp['composicao'], $formComp['percentComp']);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.