0

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>');

});
6
  • 2
    what is the expected output? Commented Jul 9, 2016 at 15:41
  • 1
    Wait why are you using stringify? That changes it back into just string. Commented Jul 9, 2016 at 16:14
  • 1
    PS: if your problem isn't solved yet, you're going to need to provide us with more source like the HTML as well. Good spot @prodigitalson that's going to be important here Commented Jul 9, 2016 at 16:14
  • 1
    It was apparently solved by removing the JSON.stringify call... Commented Jul 9, 2016 at 16:14
  • @prodigitalson yes, I solved the problem deleting that part Commented Jul 9, 2016 at 16:21

4 Answers 4

2

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'
    );
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is a nice solution, easier than what I did, thank you
2

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.

2 Comments

result.length works? because it didn't work with me when I tried it because the result is an object
You have not used dataType: "json" during the request and this was not needed var data = JSON.stringify(info); result.length it given you the count. Thanks. Hope your problem is solved.
1

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.

6 Comments

@Vladmir You mean data[0].name?
@ProfessorZoom If you're getting the correct response, you should be able to use that or [].forEach.
@IsiahMeadows but it is not displaying nothing, just this in console log jquery-1.12.4.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"name":"prueba 2","quantity":"4","price":"100"}] but beside that nothing
Try Array.prototype.forEach, i.e. info.forEach(function (entry, index) { /* ... */ }).
I just did notice that if I remove JSON.stringify part it shows the values, so the problem could be it?
|
1

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

1 Comment

So you are attempting to read a javascript variable inside PHP code?

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.