Why this json encode format is not working .If I write it outside of the all brackets.Then it works,but get only one row.Plz help
$sql=mysqli_query($database,"SELECT * FROM com ORDER by time DESC");
while($row=mysqli_fetch_array($sql)){
$mid=$row['id'];
$text=$row['text'];
if($text) {
$response=array();
$response['msg']=$text;
$response['id']=$id;
echo json_encode($response);
}
}
//$response=array();
// $response['msg']=$text;
// $response['id']=$mid;
// echo json_encode($response);
Jquery for getting above results.
function com(id){
$.post('load.php', {tocom:id},function(data) {
var json = eval('(' + data + ')');
if(json['msg'] != "") {
var msg=json['msg'];
var fro=json['id'];
$("#msg).html(fro+msg);
}
});
}
You are not giving one json response, but as much response as you have iterations in your while.
The good syntax should be :
PHP :
$sql=mysqli_query($database,"SELECT * FROM com ORDER by time DESC");
$final_response = array();
while($row=mysqli_fetch_array($sql)){
$mid=$row['id'];
$text=$row['text'];
if($text) {
$response=array();
$response['msg']=$text;
$response['id']=$id;
$final_response[] = $response;
}
}
echo json_encode($final_response);
JS :
function com(id){
$.post('load.php', {tocom:id},function(data) {
$("#msg").html('');
var json = eval('(' + data + ')');
$.each(json, function(i, row) {
if(row['msg'] != "") {
var msg=row['msg'];
var fro=row['fro'];
$("#msg").append(fro+msg);
}
});
});
}
You are posting the json right after you read the first entry from the mysql result. That produces a json construct which terminates your reply for the querying client side.
Instead you have to collect all rows into an array inside php first and THEN convert the whole array into a json structure.