I don't quite understand how to fetch data from MySQL database using ajax. I've read a lot through internet but still I'm not able to find an answer.
<script src="js/jQuery.js"></script>
<script type="text/javascript">
setInterval(function(){
$(function ()
{
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
console.log(data);
}
});
})
}, 1000);
</script>
<?php
include("connect.php");
$link=Connection();
$result = mysqli_query($link, "SELECT * FROM `estacionamiento' ORDER BY timeStamp DESC");
$data = array();
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
echo json_encode($data);
var_dump($data);
?>
My table 'estacionamiento' is structured by 4 columns which are (timeStamp, dir1, dir2, state). So from my above code, I want to receive these variables that will be changing over the time, so that's why I put setInterval. As far as I know, when I encode json those variables, it sends an object to my javascript... but I need them as string variables in my javascript. Also I'm not able to see anything in web console where I'm supposed to see because of console.log(data)
. Finally, I want to know if there's a way to see if I'm sending correctly $data
from php code.
Btw, I've done this before but just sending one variable and It was by execute statement php. I'm not familiar with this code.
<?php
include("connect.php");
$link=Connection();
$stmt = $link->prepare("SELECT estado FROM estacionamiento ORDER BY timeStamp DESC"); /* PREPARE YOUR QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($estado); /* BIND RESULT TO THIS VARIABLE */
$stmt->fetch(); /* FETCH RESULT */
$stmt->close(); /* CLOSE PREPARED STATEMENT */
echo $estado;
?>
EDIT: The error visible in Chrome's developer tools: