Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve data from PHP file using $.getJSON

Tags:

javascript

php

I'm trying to set up a comments system on photos.


I understand how to use $.getJSON when the array is 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 complex thing.


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

For example let's say we're trying to retrieve the comment data from the photo with

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 encode it:

echo json_encode($comments);

Which prints something like this (the 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 the comments array?

$.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?
});

Additionally, I have two json arrays that need to be echoed within the same PHP file. i.e. echo json_encode(array('img1'=>$img1link)) and echo json_encode($comments); need to be echoed within the same PHP file, but it made the code stop working altogether.

like image 839
frosty Avatar asked Apr 01 '26 19:04

frosty


1 Answers

If you want to display the comments you need to loop 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 JSONs you need to combine them into one JSON object.

echo json_encode(array('img' => $img1link, 'comments' => $comments));
like image 181
jcubic Avatar answered Apr 03 '26 08:04

jcubic