I’m pretty new to ajax (via jQuery) and JavaScript. What I would like is to execute a php script periodically (and asynchronously) that fetches some SQL data. However I will present this data in a JavaScript graph, so I need it to get back into my JavaScript.
I tried an embedded php script inside the JavaScript that pushes the SQL data into an array, and then simply fetches the page itself with .ajax call, but this did not work (even though I could see in the page source that the JavaScript was changed, the graph did not respond to the changes):
ajax.php (not working):
$(function () {
function fetchData() {
$.ajax('ajax.php');
<?php
try
{
$now = time();
$query = "select * from jet_pressure;"
$result = $db->query($query);
foreach ($result as $row)
{
print "d1.push([".$row['timestamp'].",".$row['unknown']."]);";
}
}
catch (Exception $e)
{
print 'Exception : '.$e->getMessage();
}
?>
$.plot($("#placeholder"), [ d1]);
setTimeout(fetchData, 5000);
}
setTimeout(fetchData, 500);
});
What is the recommended way to do this?
I think you are mixing up your concepts. PHP only runs on the webserver. Javascript runs on the client (ie the web browser)
If you create a page with the
.phpextension as in yourajax.php, it will be served from you web server once and everything it contains that’s a in the<?php ?>block will be parsed by the server – it not dynamic.The resultant page contains parsed values from your php script, but not the script itself.
Javascript operates on the users computer, and therefore handles the user interaction and events on the web page. You can use Javascript to call a server script (in this case php) when you need to get data from the server. That is basically what AJAX is all about. But generally the javascript is contained in files ending
.jswhich tend not to be parsed by your webserver, unless the javascript is actually included in your page, but that’s not really how to do things these days.I have no idea what you are tring to do by mixing javascript with php. This is not AJAX.
I suggest you use something like JSON. This rough php script first to compile your results into JSON, then the javascript ajax call. You’ll need to have included the JQUERY library and save the whole php script as a seperate file called
getdata.php.Javascript: