Pass multidimensional array to php

Asked

Viewed 610 times

0

I’ve been struggling with a problem for days..

Here’s the thing, I have a multidimensional array and I want to pass as a parameter in a request ajax for a php file , however when I’m doing this what is returning me is a php empty. I have no idea why , I researched and found nothing that corresponded to my doubt.

If anyone can give me a light!

Follow the code!

// Criando o array global
var dados = new Array();
dados[contador] = new Array();
dados[contador]['usuarios'];
dados[contador]['quantidade'];

var usuario = false; //Verificando se usuario já existe for (var i = 0; i < dados.length; i++) { if (dados[i]['usuarios'] === usuarioDivisao) { dados[i]['usuarios'] = usuarioDivisao; dados[i]['quantidade'] = $("input[name='mailing_quantididade_html']").val(); usuario = true; break; } } if (!usuario) { dados[contador] = new Array(); dados[contador]['quantidade'] = $("input[name='mailing_quantididade_html']").val(); dados[contador]['usuarios'] = usuarioDivisao; contador++; } $("input[name='mailing_quantididade_html']").val("");

After populating them I am passing as parameter to the php file

$('.atualizar').click(function () {
    $.ajax({
        url: 'Mailing/exportar.php',
        type: 'POST',
        data: {dados:  JSON.stringify(dados), caminho: 'MailingTemp/qualquernomeOcidental2.csv', usuario: usuarioDivisao},
        beforeSend: function () {
            $(".mailing #aguarde_pequena2").fadeOut(200);
            $(".mailing #aguarde_pequena").fadeIn(200);
        },
        success: function (data) {
            alert(data);
        }
    });
});
  • Try to set the type of data you are passing in ajax: dataType: 'json'

  • Tries to send directly as an array, without using the JSON.stringify.

  • Man if you want to pick up via $_POST php must quote values in js. Ex: {"dados": dados, "caminho":caminho}

  • I tried everything you said , but it did not, thanks! But I gave an Alert in the array and it is coming empty before going to ajax requisão, could the problem be this ? He is sending php an empty array, but it fills normal, only at the time of sending it appears empty.. Any idea ?

  • Periotto, I’ve done this before with a simple array, the difference now that this array is more complex. I’m picking with the GetPost, I’m doing so in php: $arrayDados = json_decode(stripslashes(GetPost('dados')));

  • Shows the whole code where vc mounts the array(for, while, etc)

  • Beauty, I’ll edit the question!

  • Man you’re wearing dados.lenght.The for will never run pq there is no record in the array

  • Precisely , if there is no record in the array and it adds , if it does not replace.

Show 4 more comments

1 answer

0


If you use an index string, when accessing an array, Javascript will reset the array to a default object, and all methods and properties of Array will produce undefined or incorrect results.

Behold:

var dados[0] = new Array();
dados[0] = new Array();
dados[0]['usuarios']; // neste momento dados[0] passa a ser um objeto do js
//para acessar o dado use: dados[0].usuarios;
//JSON.stringfy(dados); retornará "[[]]" por causa da despadronização do array

You can mount your array like this for example:

var dados[0] = new Array()
dados[0] = {usuarios:0, quantidade:0};
dados[1] = {usuarios:1, quantidade:1};

Ajax:

$('.atualizar').click(function () {
    $.ajax({
        url: 'Mailing/exportar.php',
        type: 'POST',
        data: {dados:  JSON.stringify(dados), caminho: 'MailingTemp/qualquernomeOcidental2.csv', usuario: usuarioDivisao},
        dataType: 'json', //Lembrado pelo Luis Henrique
        beforeSend: function () {
            $(".mailing #aguarde_pequena2").fadeOut(200);
            $(".mailing #aguarde_pequena").fadeIn(200);
        },
        success: function (data) {
            alert(data);
        }
    });
});

In PHP:

$arrDados = json_decode($_POST['dados']);
  • So, thank you so much for the touch! So that changes my entire function , as I did not know that then I was a bit confused.. How am I going to pass a value to that array ? For example: I was doing so dados[contador]['usuarios'] = usuarioDivisao;, like I’m gonna do now ?

  • //Something like this @Marloncastro var data = new Array(); var input = $("input[name='mailing_quantididade_html']"); data[counter] = {users : 0, quantity:0}; var user = false; for (var i = 0; i < data.length; i++) { if (data[i].users === userDiving) { data[i]. users = userDiving; data[i]. quantity = input.val(); user = true; break; } } if (!usuario) { data[counter] = { users: input.val(), quantity: userDivision } counter++; } input.val("");

  • That’s right, thanks @Dougladesouza.. I’m only having trouble accessing this matrix in php , but the first step was taken! Thanks!

Browser other questions tagged

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