Reputation: 25
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);
});
}
});
});
Upvotes: 1
Views: 45
Reputation: 32354
Use mysqli_fetch_all()
if(mysqli_num_rows($sql)>=1){
$mem = mysqli_fetch_all($sql,MYSQLI_ASSOC);
echo json_encode($mem);
}
Upvotes: 1
Reputation: 2949
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);
}
Upvotes: 2