Retrieving data from PHP file using $ .getJSON

I am trying to create a commenting system on photos.


I understand how to use $ .getJSON when the array looks like this:

get.php:

$var = 5;
echo json_encode(array('var'=>$var));

      

main.php:

$.getJSON("get.php",function(data){
    number = data.var; // number = 5
});

      

But I have a more complicated thing.


My comment table has these 4 columns: id | photo_id | Comment | date

For example, lets say we are trying to get comment data from a photo using

photo_id == 1

...

We don't know how many comments there might be.

In getcomments.php:

$photoid = 1;

$comment = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photoid'");

while($commentrow = $comment->fetch_assoc()) {
    $comments[] = $commentrow;
}

      

Then you code it:

echo json_encode($comments);

      

Which prints something like this (photo has 2 comments):

[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]

      

How do I declare variables for an array of comments?

$.getJSON("getcomments.php",function(data){
    // how do I declare variables for the comments array, especially since you don't know how many there might be?
});

      


Also, I have two json arrays that need to be echoed in the same PHP file. those. echo json_encode(array('img1'=>$img1link))

and echo json_encode($comments);

should be echoed within the same PHP file, but that caused the code to stop working altogether.

+3


source to share


3 answers


If you want to display comments you need to iterate over the array. You can use for loop or forEach function.

$.getJSON("getcomments.php",function(data){
    data.forEach(function(comment) {
        $('div').append('<span>' + comment.comment + '</span>');
    });
});

      



To display two JSON, you need to combine them into one JSON object.

echo json_encode(array('img' => $img1link, 'comments' => $comments));

      

+3


source


[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]

      

Using this JSON data

is an array and you have to manage it like an array. You can scroll through it with the help of simple cycles ( for

, while

...) or use a new functional methods, such as forEach

, map

, filter

....



Try this example:

$.getJSON("getcomments.php",function(data){
    data.forEach(function(item, index, all) {
        console.log(item.comment);
    });
});

      

0


source


Declare an object and push it into an array.

var commentsArr = [];

for (var i = 0; i < data.length; i++) {
    var objToPush = {
        id: data.id,
        comment: data.comment,
        date: data.date
    }

    commentsArr.push(objToPush);
}

      

0


source







All Articles