Recover mysql php query with ajax

Asked

Viewed 465 times

0

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

php page (make the 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 (calls 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)
});
}});
  • You checked if php is returning the expected in the request?

  • Yes using load returns normal data!

1 answer

1

You can turn all your variaveiz into a json so:

$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 uses the getJson

$.getJSON("seu_php.php", function(result){
    $.each(result, function(i, field){
      alert(field);
    });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.