Link to home
Start Free TrialLog in
Avatar of Sucao
Sucao

asked on

How do I get multiple rows of data with PHP using Mysql, send it JSON encoded with ajax, and then read it with javascript/jquery

I am pretty new to combining codes so I need some help. I want to grab the comments for a particular article and put them on the webpage. I can do this when I just find 1 row, but I don't know how to grab multiple rows of data from a database using PHP, JSON encode it, then grab it with ajax, decode it and loop through the rows with javascript on the main page.

When I do the PHP code by itself it shows "{"ID":"1","comment":"this is the first comment"}{"ID":"2","comment":"this is the second comment"}{"ID":"3","comment":"this is the third comment"}" I don't know if this is the proper format for the javascript to read it.

I also, never get to the alerts in the javascript.

Thanks for your help.
/*****************here is javascript that I've been using on index.html*******************************/
 
$.getJSON('../advice/php/get_comments.php', ' ', process_comments);
function process_comments(data) {
var new_comment = data.comment;
var ID = data.ID;
alert('new_comment'+ new_comment);
alert('ID'+ID);
}
 
 
 
 
/*****************here is get_comments.php*******************************/
 
<?PHP
include("../../php/mysql.php"); //gets the mysql info.
 
 
 
$get_comments_sql = "SELECT ID, comment
					FROM comments
					WHERE ID = articles_ID = 47
					GROUP BY ID";
		if ($result = mysqli_query($mysqli, $get_comments_sql)) {
			while ($row = mysqli_fetch_array($result)) {
				$array_data = array('ID'=>$row[0], 'comment'=>$row[1]);
				echo json_encode($array_data);
			}
		}
?>

Open in new window

Avatar of alien109
alien109
Flag of United States of America image

you only want to echo the json string once. So rather than doing it for every row, try building an array of rows, and then encoding that.

Avatar of Jonah11
Jonah11

ya, basically if you switch lines 28 and 29 in your code it should work
oh and also process comments needs to account for the fact that data is an array...
Avatar of Sucao

ASKER

Ok, so I've learned that I want to only echo the JSON string once. I switched lines 28 and 29. How do I send out an array of rows. Could someone write an example using this code? Also, what do I need to change in my javascript to access that JSON encoded array of rows?
ASKER CERTIFIED SOLUTION
Avatar of Jonah11
Jonah11

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sucao

ASKER

Jonah11 that's perfectly what I needed. I have one final part to figure out though, how do I loop through the data with javascript? right now I am only getting alerts about the first row of data.