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

Different Links For Iframe jQuery Modal

jquery ajax iframe modal-dialog

i have some jquery code to show iframe in modal window.

b2RevoluteJoint in cocos2d

c++ ios objective-c cocos2d-iphone box2d

I have a CCNode subclass that is composed of a rectangular sprite that rotates around an anchor point. My object gets displayed in the world but I can't seem to get the b2RevoluteJoint working prop...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.