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>