Retrieve php mysql query with ajax

0

Hello! I would like a help to know how to recover data from the php mysql query and present it on the page that made the request via ajax, this code currently displays error 'can not read property' items' of null. I would like to retrieve the separate items because the goal is to create new elements regarding the name, message etc. e.g. < div > + item.f + < / div>

php page (query)

if ($_GET['action'] == "chatheartbeat") { chatHeartbeat(); }
function chatHeartbeat() {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$items = '';
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$items .= <<<EOD
{
"s": "0",
"f": "{$chat['de']}",
"m": "{$chat['mensagem']}",
"i": "{$chat['img']}"
 },
EOD;
}

Index (call the query to display the result)

$.ajax({
  url: "asd.php?action=chatheartbeat",
  cache: false,
  dataType: "json",
  success: function(data) {
$.each(data.items, function(i,item){
alert(item.f)
});
}});
    
asked by anonymous 21.09.2016 / 04:46

1 answer

0

You can turn all your variave into a json like this:

$sql = "select * from mensagens";
$query = mysql_query($sql);
$chat = mysql_fetch_array($query);
echo json_encode($chat,TRUE);

and to get the request in ajax use getJson

$.getJSON("seu_php.php", function(result){
    $.each(result, function(i, field){
      alert(field);
    });
});
    
18.12.2018 / 13:27