Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realtime Update with Jquery, AJAX,PHP & Arrays

Tags:

jquery

ajax

php

So, I'm trying to learn Jquery/AJAX using an array to execute and update code on different elements within a single function.

Below, I'm trying to update the DIVs with the number of people logged into the site, and the total currency in circulation. The script will update every few seconds.

Can anyone help me correct my syntax or at least tell me what I'm doing wrong here?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="../jquery.js"></script>

<script type="text/javascript">
function updateStats(stat)
{
    var stat = ["online","money"];

    var url = "online.php";

    $.each(stat,function(){

    $.post(url,{stat: stat} , function(data) {

        $("#" + this).html(data);       
    })

    })  
} 

setInterval('updateStats("updateStats")', 2000);
</script>


<body onLoad="updateStats(stats);">

<div id="online"></div>
<div id="money"></div>
</body>
</html>

<?php

if($_POST['stats']=='online')
{
    $result= $mysqli->query("SELECT loggedin FROM accounts WHERE loggedin !=0");
    echo $result->num_rows; 
} 

elseif($_POST['stats'] == 'money')
{
$result = $mysqli->query("SELECT sum(money) AS totalMoney FROM users");
$getData = $result->fetch_assoc();

echo number_format($getData['totalMoney']);

}

$mysqli->close();

?>
like image 840
prosportal Avatar asked Jan 20 '26 23:01

prosportal


2 Answers

Your code should look like:

function updateStats(stat)
{
    var stat = ["online","money"];
    var url = "online.php";

    $.each(stat, function(i, key){
       $.post(url, {stats: key}, function(data) {
          $("#" + key).html(data);       
       });
    });
} 

Please also note the stats parameter in plural.

like image 160
Garis M Suero Avatar answered Jan 22 '26 14:01

Garis M Suero


Here:

$("#" + this).html(data); 

this in that situation refers to a different this than what you are expecting. Try this instead:

$.each(stat,function(i,str){
    $.post(url,{stats: str} , function(data) {
        $("#" + str).html(data);       
    });
});

Update Fixed param name as per Rory's comment.

like image 24
Kevin B Avatar answered Jan 22 '26 12:01

Kevin B