cs-smith cs-smith - 2 months ago 5
JSON Question

ajax not responding with all array data

ajax comes back with 1 element of an array (data from mysql database) instead of all rows, pls help:

php code:

<?php
header("Content-type:application/json");
$srchString = trim($_POST['q']);
$sql = mysqli_query($connect,"SELECT * FROM dbname.tblname
WHERE fieldname LIKE '%$srchString%' LIMIT 7");
confirmQuery($sql);
if(mysqli_num_rows($sql)>=1){
$mem = mysqli_fetch_array($sql,MYSQLI_ASSOC);
echo json_encode($mem);
}
?>


js:

$("#q").on("keyup",function(){
var q = $(this).val();

$.ajax({
type: "POST",
dataType:"json",
url:"process.php",
cache:false,
data:"q="+ q,
success:function(data){
$.each( data, function( key, value ) {
console.log(value.tel);
});
}
});
});

Answer

You have to iterate over all fetched rows and put them into an array. After that you are able to call json_encode to get a JSON array.

Please replace

if(mysqli_num_rows($sql)>=1){
      $mem = mysqli_fetch_array($sql,MYSQLI_ASSOC);
      echo json_encode($mem);
}

with

if(mysqli_num_rows($sql)>=1) {
    $rows = array();      
    while($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)) {
        $rows[] = $row;
    }
    echo json_encode($rows);
}
Comments