2

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?

5
  • 1
    Post your code for the Javascript side, and do a console.log() of the array in the JavaScript. Commented Feb 14, 2016 at 3:32
  • You cannot send a PHP array to javascript. I mean, these are two different languages. Your best choice is delivering JSON to your javascript as a response that you have parsed with PHP. You usually do that when you send an Ajax request with javascript, and you process it with PHP. There you can convert a PHP array into a json respresentation and send it back in the response. Commented Feb 14, 2016 at 3:33
  • You need to read an AJAX tutorial. And do some google searches. To call this question a duplicate would be a radical understatement. Commented Feb 14, 2016 at 3:40
  • I updated the code with what i am actually using. Commented Feb 14, 2016 at 4:08
  • 1
    that's not how multidimensional arrays work. $data[1][0]= 'some more content'; will rewrite what's in the data[1]= 'some content'. think of $data[1] as of a box which can store either a value 'some content' more more boxes, which will be an another array Commented Feb 14, 2016 at 4:14

3 Answers 3

2

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.

1
  • Yeee Ha! This is working now i have to figure out my coding all over but hey. It wouldnt be no fun otherwise. Thank you Commented Feb 14, 2016 at 5:04
1

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.

2
  • There shouldn't be anything wrong with json_encode, you shouldn't have to manually encode the data structure. Commented Feb 14, 2016 at 4:38
  • The issue is that the the attempt of constructing a multidimensional array was wrong, data[1] = 'something', data[1][0] = 'something else'. Basically just modifying strings rather than adding a child array Commented Feb 14, 2016 at 4:39
1

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'
1
  • Sounds like what I need I will try it out. Thank you Commented Feb 14, 2016 at 4:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.