Professor Zoom
Professor Zoom

Reputation: 349

How to convert an object from PHP to an Array in Javascript?

I'm trying to convert an object that I get from PHP into an array in Javascript but I don't know how to solve this, I try some solutions I read before do this question but it doesn't work, I got something like this in PHP

$data = explode(',', $articles);

$length = count($data);

for ($i = 0; $i < $length; $i++) {

    $products = explode('-', $data[$i]);

    $product_key = $products[0];
    $quantity    = $products[1];

   $get_data_product = mysqli_query($connection, "SELECT * FROM articles WHERE id_article = '".$product_key."' AND id_user = '".$id_user."'") or die (mysqli_error($connection));
   $get_data_product = mysqli_fetch_assoc($get_data_product);
   $article_name     = $get_data_product['name'];
   $article_price    = $get_data_product['price'];


   $info[$i] = array('name' => $article_name, 'quantity' => $quantity, 'price' => $article_price);
}

echo json_encode($info);

And in Javascript

success: function(info) {

   var data = JSON.stringify(info);

   console.log(data);
}

Console log show this

[{"name":"prueba 2","quantity":"4","price":"100"}]

I tried to read them all with ths code but it is showing data, only when I use console log or alert

 $.each(data, function(i) {

   $('#content').append('<tr class="text-center">' +
                            '<td>' + data[i].quantity + '</td>' +
                            '<td>' + data[i].name + '</td>' +
                          '</tr>');

});

Upvotes: 0

Views: 101

Answers (4)

Jonathan
Jonathan

Reputation: 11494

As prodigitalson notes in the comments - and is effectively the answer - you converted your data into a JSON object in PHP, but then convert it needlessly into a string, so you then can't manipulate it at all.

E.g: JSON.stringify([{test: 1}]) becomes "[{test: 1}]".

Removing that, you will then be able to loop on it in your original way, or you can loop on it using a standard javascript foreach where data is your response in your callback containing [{"name":"prueba 2","quantity":"4","price":"100"}]:

data.forEach(function (e) {
    $('#content').append(
        '<tr class="text-center">\n' +
            '<td>' + e.quantity + '</td>\n' +
            '<td>' + e.name + '</td>\n' +
        '</tr>\n'
    );
});

Upvotes: 2

Dipesh Sukhia
Dipesh Sukhia

Reputation: 101

your console.log(data); show json arry that is [{"name":"prueba 2","quantity":"4","price":"100"}]

try this

$dataobj = data1=json_decode(data);

$arry = (array) $dataobj;

try this code

Upvotes: 1

Saibal Roy
Saibal Roy

Reputation: 431

PHP End Sample Code:

<?php 
for ($i = 0; $i < 3; $i++) {
    $quantity=rand(5,10);
    $price=rand(500,1000);
   $info[$i] = array('name' =>'prueba'.$i, 'quantity' =>"$quantity", 'price' => "$price");
}

echo json_encode($info);
?>

JQuery End:

<!DOCTYPE html>
<html>
<head>
    <title>Json</title>
     <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
     <script type="text/javascript">
        $(document).ready(function(){
            $.ajax({ type:"POST", url: "array.php",  dataType: "json", success: function(result){
                    console.log(result);
                    for(i=0; i<result.length;i++)
                    {
                        console.log(result[i]);
                        console.log(result[i].name);
                        console.log(result[i].quantity);
                        console.log(result[i].price);
                    }

             }});

        });

     </script>
</head>
<body>

</body>
</html>

Sample Response in the test:

[{"name":"prueba0","quantity":"8","price":"574"},{"name":"prueba1","quantity":"8","price":"555"},{"name"
:"prueba2","quantity":"7","price":"901"}]

Reference : http://www.jsoneditoronline.org/?id=5e23cd942a949e86545fa320a65ff0e7

Hope this solves your problem. Thanks.

Upvotes: 2

Alonso Urbano
Alonso Urbano

Reputation: 2264

I think your code is fine, if you do this in javascript code:

success: function(info) {

   var data = JSON.stringify(info);

   alert(data[0].name);
}

That alert should show the expected value of name property of data object.

Upvotes: 1

Related Questions