MadeInDreams
MadeInDreams

Reputation: 2126

PHP to Javascript multidimensional array

I'm trying to send a PHP array to Javascript.

So far i was only sending a single array in Json to my javascrpt ajax;

The PHP part so far works like that;

If I have an error in my request;

$data[0] = 'false';
$data[1] = 'Error message';

If there is no error;

$data[0] = 'OK';
$data[1] = 'html content to display';

I want to send multidimensional array like;

 $data[0] = 'OK';
 $data[1] = 'html content to display';

 $data[1][0] = 'OK';
 $data[1][1] = 'another html content to display';

The Javascript function that passes the request;

function load(action,container){
    return new Promise(function (resolve, reject) {
        //alert(container);
        $.ajax({
            url: '/ajax.php',
            type: 'post',
            dataType: 'json',
            data: { 'query': 'true', 'action': action, 'container': container },
            success: function (data, status) {
                console.log(data[0] + ' : FOR ' + action);
                if (data[0] === 'false') {
                    $("#errorBox").addClass('visible');
                     for (var i = 1; i < data.length; i++) {
                        $('#errMsg').append(data[i]+'<br>');
                        $('#console').prepend('<span class="consoleError">ERREUR : </span>' + data[i] + '<br>');
                    }
                    $("#errorBox").show();
                }
                else if (data[0] === 'OK') {
                    resolve(data);
                    $(document).ready(function () {
                     $('#console').prepend('<span class="consoleGood"> Statue: ' + data[0] + '</span> Requête: ' + action + ' Conteneur:' +container+ '<br>');
                    data.splice(0,1);
                });
              }
                return;
            },
            error: function (xhr, desc, err) {
                console.log(xhr);
                console.log("Details: " + desc + "\nError:" + err);
                return;
            }
        }); // end ajax call
    });//promise 
};

On the PHP part I use ;

$data[0]= 'OK';
$data[1]= 'some content';
$data[1][0]= 'some more content';

echo json_encode($data);

I can get all the data contained in the first level of the array but not the second level.

The console log is showing me:

"<div class="doc_css"><div class="doc_status">active</div><h1>Mon document</h1><p>Le corp de mon document</p><div class="doc_post_nfo">Originalement posté par 1 le 2016-02-13 15:25:35<div class="doc_edit">Modifier</div></div></div>"
length: 1
__proto__: Array[0]

So what do I have to do the get the second level of the array?

Upvotes: 2

Views: 456

Answers (3)

Pik&#39;
Pik&#39;

Reputation: 7077

I ran your PHP code and var_dump'ed the $data variable.

<?php   
$data[0] = 'OK';
$data[1] = 'html content to display';

$data[1][0] = 'OK';
$data[1][1] = 'another html content to display';

var_dump($data);
?>

Here is what I got:

array(2) {
  [0]=>
  string(2) "OK"
  [1]=>
  string(23) "Oaml content to display"
}

So your array is not multidimensional. Also note the first characters of the second element. Guess what happened?

When you create a string in PHP, you can access individual characters as if the string was an array (well, technically, strings are character arrays). So:

<?php
$str = 'abcde';
$str[2] = 'k';
// Now $str contains "abkde"
?>

So that's what happened. You changed the first and then the second character of $data[1].

<?php
$data[1] = 'html content to display';
$data[1][0] = 'OK';
// Now $data[1] contains "Otml content to display"
$data[1][1] = 'another html content to display';
// Now $data[1] contains "Oaml content to display"
?>

A multi-dimensional array is an array containing arrays. PHP create arrays on the spot when you use the bracket notation, but of course if the variable (or array cell) alreay contained a string it interprets the brackets as an access to individual characters.

This works:

<?php   
$data[0][0] = 'OK';
$data[0][1] = 'html content to display';

$data[1][0] = 'OK';
$data[1][1] = 'another html content to display';

echo json_encode($data);
?>

It prints [["OK","html content to display"],["OK","another html content to display"]], which the Javascript code can parse and use after retrieving.

Upvotes: 2

bowpunya
bowpunya

Reputation: 126

maybe you can do it better this way

$data = [['code'=>true,'message'=>'Error message'],['code'=>'OK','message'=>'Other message']];

then do

json_encode($data);

on javascript you can get (by convert to json via ajax like you did)

data[0].code // will be true
data[1].message // will be 'Other message'

Upvotes: 1

LuvnJesus
LuvnJesus

Reputation: 631

I'm not going to repeat your entire scenario with this answer, but I've had the same need .. to get my PHP array's into javascript. All I did was use PHP to create a Javascript function (or simple JS code) that set the array values. Here's a conceptual example. You can apply to your situation:

First, the basic PHP array:

<?php
$a[1] = "Mike";
$a[2] = "Jim";
$a[3] = "Mark";
$a[4] = "George";
?>

To get this array in to Javascript, I would do something like:

<?php
print "<script type='text/javascript'>\n";
   foreach ($a as $key => $val) {
      print "a[$key] = \"".$val."\";\n";
   }
print "</script>\n";
?>

This produces:

<script type='text/javascript'>
a[1] = "Mike";
a[2] = "Jim";
a[3] = "Mark";
a[4] = "George";
</script>

It's a fudgy way to do things but it works. Of course this is a very stupid/basic example but it does show one way to get a PHP array into JS.

Upvotes: 1

Related Questions