jQuery: mysql row data

Hello

I have a .load that executes a php mysql query from another page.

This query displays all the data of the database.

Each result is wrapped around a div.

<div id =“post<? echo $row[‘post_id’]; ?>”>

the id of the div depends on the post id of the result.

How do I put the data of $row[‘post_id’] in my javascript?

you can assign post_id to a javascript variable like this

<script type="text/javascript">

var myVar = <?php echo row['post_id'];  ?> ;

alert(myVar);

</script>

Hi, I cannot do this because ajax calls do not process inline javascript.

You can use JSON - using json_encode on the PHP side, then using a getJSON on the jQuery side:

Example:
PHP - test.php:

<?php

	echo json_encode(
		array(
			array(
				'id' => 1,
				'title' => 'Test1'
			),
			array(
				'id' => 2,
				'title' => 'Test2'
			),
			array(
				'id' => 3,
				'title' => 'Test3'
			)
		)
	);

?>

HTML/JS


<!DOCTYPE html>
<html>
	<body>
		<div id="testDiv"></div>
		
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
		<script>
		$.getJSON(
			'test.php',
			function(data) {
				var items = '';
				$.each(data, function(i) {
					items +='<p id="post_' + data[i].id + '">' + data[i].title + '</p>';
				});
				$('#testDiv').html(items);	
			}
		);		
		</script>
	</body>
</html>

Hi, thank you for your response.

How I would I use json_encode on a while loop?

pretty much like the getJSON example I showed before:

  • Call an empty array before the while loop
  • Then populate the array in the loop
  • Then encode the array when your out of the loop.

Here is another example using an sqlite database that can be used with the HTML example above:


<?php

	error_reporting(-1);

	$db = new PDO('sqlite::memory:');
	$db->exec('CREATE TABLE test(id INTEGER PRIMARY KEY, title VARCHAR NOT NULL UNIQUE)');
	$db->exec('INSERT INTO test VALUES(1, "Title 1")');
	$db->exec('INSERT INTO test VALUES(2, "Title 2")');
	$db->exec('INSERT INTO test VALUES(3, "Title 3")');	

	$arr = array();
	foreach( $db->query('SELECT * FROM test', PDO::FETCH_ASSOC) as $row ) {
		$arr[] = $row;
	}
	echo json_encode($arr);

?>

Hi, thank you for your response. I have it working now.
Last question, I noticed all the html for the output is in the javascript. Is there a way to put it outside the javascript?

Thanks