Reading php array with jquery and appending to a div?

I'm trying to get a column from mySQL as an array in php, then read this into javascript with jquery/ajax, and finally display the first four of the array within some HTML divs.

I think I have the php working because when I inspect I get a return that has all the elements in the array.

retrieve.php

//Create connection ("Server", "Login name", "Password", "Database name")
$connect = mysql_connect($host, $username , $password); 
 //Check connection
if (!$connect)
{
    die ('could not connect: '. mysql_error());
}

//create connection and select database
mysql_select_db($database, $connect);

//select text column and orders them by most recent postID
$query = "SELECT text FROM $table ORDER BY postID DESC";
$result = mysql_query($query);

//create an array of recent responses
while($row = mysql_fetch_array($result)){
    echo json_encode($row['text']);
}

mysql_close($connect);

scripting.js

$(document).ready(function(){  //This performs specified actions when the page fully loads

$.ajax({
    type: 'POST',
    url: 'retrieve.php',
    data: 'data',
    dataType: 'json',
    success: function(result){
        $("#box0").html(result[0])
        $("#box1").html(result[1])
        $("#box2").html(result[2])
        $("#box3").html(result[3]);
    }
});

Answers


Try replacing

while($row = mysql_fetch_array($result)){
    echo json_encode($row['text']);
}

with

$rows = array();
while($row = mysql_fetch_array($result)){
    $rows[] = $row['text'];
}
echo json_encode($rows);

to json encode an array of row texts rather than encoding them separately.


Need Your Help

jquery method as a javascript's class method

javascript jquery

is it possible to insert a jquery function in a javascript class?

Set tag of a ListBox item

vb.net winforms

Is it possible to set the Tag property of an individual item of the ListBox instead of only the whole control?