0

I have an array in PHP and I would like to loop through it.

Unfortunately, the array gives back this in JavaScript:

Array
(
    [data] => 12,11,2,5,6,7,8,9,10,13,14,15,16,17,18
    [0] => 12,11,2,5,6,7,8,9,10,13,14,15,16,17,18
)

And not:

var myvar = [10, 11, 12, ...];

So I cannot loop through it. Any suggestions?

<?php
    include("connection.php");

    $query = $handler->query('  SELECT data FROM lista where id=1;');
    $query->setFetchMode(PDO::FETCH_BOTH/*, 'CreaPrezzi'*/);
    $r = $query->fetch();

    print_r($r);

    $.ajax({
        type:"POST",
        url:"getSortable.php"
    }).done(function (list) {

        var sortedList = list;
        sortedList.forEach(function(id) {
           $("#" + id).appendTo("#sortable")
        })

    })
cbmeeks
  • 11,248
  • 22
  • 85
  • 136
user3187960
  • 295
  • 2
  • 14
  • 1
    use `json_encode()` when printing the array, – Sirko Dec 07 '16 at 18:51
  • 1
    Possible duplicate of [Convert php array to Javascript](http://stackoverflow.com/questions/5618925/convert-php-array-to-javascript) – Mahi Dec 07 '16 at 18:55

2 Answers2

1

That kind of output is indeed what you get with print_r. Instead use json_encode as follows:

echo json_encode($r[0]);

Then in JavaScript indicate that your are expecting JSON:

$.ajax({
    type:"POST",
    url:"getSortable.php",
    dataType: "json"    // <!-- add this
}).done( // ...etc

As $r[0] (in PHP) is a plain string, you'll need to split it into an array, either in PHP, or in JavaScript. In PHP that could be done with explode:

echo json_encode(explode(",", $r[0]));

Or with JavaScript (but then use the first PHP version) you can use split:

var sortedList = list.split(',');
trincot
  • 317,000
  • 35
  • 244
  • 286
-1
    <?php
    include("connection.php");


    $query = $handler->query('  SELECT data FROM lista where id=1;');
    $query->setFetchMode(PDO::FETCH_BOTH/*, 'CreaPrezzi'*/);
    $r = $query->fetch();

   echo json_encode($r);



            $.ajax({
                type:"POST",
                url:"getSortable.php"
            }).done(function (list) {

                var sortedList = list;

                sortedList.forEach(function(id) {
                    $("#" + id).appendTo("#sortable")
                })

            })
  • 1
    Please add an explanation of the changes you made and why they answer the original question. Don't post "spot the difference" style answers like this. – André Dion Dec 07 '16 at 19:01