I have a mysql database that stores data such as usernames. I have a PHP file called result which retrieves the results from the database and encodes them into a JSON string. I then want the same PHP file to output the results without a page reload (via ajax). Effectively I want the same page to get the JSON string as a HTTP request, how do I go about this
this is results.php so far
<?php
$link = mysql_connect('', '', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('test', $link);
if (!$db_selected) {
die ('Can\'t use test : ' . mysql_error());
}
$result = mysql_query("SELECT user_name FROM users");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$names = array();
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $val) {
$names[][$key] = $val;
}
}
if ($_GET['myvar'] == "done")
{
$ennames = json_encode($names);
echo $ennames;
exit();
}
?>
<script src="jquery-1.7.1.min.js">
function getJSON()
{
$.getJSON("results.php", { myvar: "done" }, function(data) {
var namesHTML = "";
$.each(data, function(key, val) {
namesHTML = namesHTML + val + "<br/>";
});
$("#divForNames").html(namesHTML);
});
setTimeOut(getJSON, 5000); //the 5000 here means 5 seconds
}
</script>
<div id="divForNames">
</div>
The only adjustment that your PHP will need for this is to add an if statement immediately after the assignment of
$ennames:For the polling, you will need to do some kind of client-side script – most likely javascript, and most easily written in jQuery. Look into the
.getJSON()jQuery function and thesetTimeOut()to create logic to do this polling. It will probably look something like this:Then somewhere in the HTML for the non-JSON page, you need to include a
<div>with the id set to match the one you using inside the$.getJSON()function (in this case, I’d need an empty<div id="divForNames">but you can change the names to fit your preferences.