0

The below code basically queries a PHP file, that queries a database for cpu_names (4 total in my test case) and the associated loads on each. I then need to take each of those four CPU times, add them together and then divide by the total number of CPUs. This essentially gets me total CPU load. So, for the test case this code upgrades 5 total CPU gauges, one of which is the total. The only problem, no matter which way I try it I can't sum these posts! Thanks.

setInterval(function() {
    fill_sum=0.0;
    $("canvas[name='gauge']").each(function(){

        var cpu_name=this.innerHTML;
        var ctx = this.getContext('2d');
        var padding = this.style.padding.replace(/[^0-9]+/, '');
        var w=this.width
        var h=this.height;
        //var fill_percent=.02;


        $.post("BH_Responder.php",
            {cpu_use: true, cpu_name: cpu_name},
            function(data, status){
                fill_percent = data;
                ctx.clearRect(0, 0, w, h);
                DrawGauge(ctx, w, h, fill_percent);


            }
        ).done(function() {
            fill_sum = fill_sum+parseFloat(fill_percent);
        });
    });

    alert(fill_sum);
    total_percent = fill_sum/<?php echo $num_rows_cpu; ?>;

    $("canvas[name='master_gauge']").each(function(){
        var ctx = this.getContext('2d');
        var padding = this.style.padding.replace(/[^0-9]+/, '');
        var w=this.width
        var h=this.height;
        //var fill_percent=.02;
        ctx.clearRect(0, 0, w, h);
        DrawGauge(ctx, w, h, total_percent);
    });
}, 100);

Section of PHP script Responder script:

}elseif (isset($_POST['cpu_use']) == true && empty($_POST['cpu_use'])==false && $_POST['cpu_use']==true){
    $cpu_name = $_POST['cpu_name'];
    $sql= mysql_query("SELECT used FROM tbl_cpu_use WHERE cpu_name='$cpu_name' ORDER BY id DESC LIMIT 1;");
    echo (mysql_num_rows($sql) != 0) ? mysql_result($sql,0,'used') : NULL;
}
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
gunslingor
  • 1,358
  • 12
  • 34
  • I wanted to introduce you to a good friend of mine, his name is [Bobby Tables](https://xkcd.com/327/) – Nir Alfasi Sep 13 '15 at 04:04
  • BTW, why can't you pass all the 4 cpu-names in one POST request, and have only *one* query to the DB that returns the total sum? – Nir Alfasi Sep 13 '15 at 04:05
  • There are many question to be asked for your script. Anyways, It would be better if you caould mention specific task which you are tryng to achieve and which is being failed... – Rayon Sep 13 '15 at 04:11
  • fill_percent is the returned value from the post, which is in the format ".05" for example, only 1 CPU name is passed to post at a time, hence the top most .each. Above I am grabbing the innerHTML at the top which returns the cpu name, 'for each', canvas. Then post that cpu name to get it's use in percent. The only problem, the only single problem, is that I need to sum the percentages and divide by four for the last section 'master_gauge'. e.g. cpu total =(cpu1+cpu2)/2. i.e. the variable fill_sum is the problem, that should help narrow the question. – gunslingor Sep 13 '15 at 04:23
  • I strongly suggest using the success or done callback to iterate – mplungjan Sep 13 '15 at 05:02

1 Answers1

1

For a good explanation of AJAX, callbacks, and all that

Looks like you're nearly there with .done() but you need to put all this stuff:

total_percent = fill_sum/<?php echo $num_rows_cpu; ?>;

$("canvas[name='master_gauge']").each(function(){ 
    ...
    DrawGauge(ctx, w, h, total_percent);
});

in the .done() callback but only call it for the last ajax response. Either keep track with a counter that you set before you make the ajax requests or if you know how many requests you'll be making on the PHP side of things.

something like:

var totalCpus = <?php echo $numCpus; // assuming you're using PHP to echo out the gauges in
// the first place. otherwise use ?>
var totalCpus = $("canvas[name='gauge']").length; // use this.
// assuming of course, that the # of gauges is the same throughout each interval
setInterval(function() {
    fill_sum=0.0;
    $("canvas[name='gauge']").each(function(){

        var numDoneRequests = 0; // this one keeps track of *dun dun dunnn* the number of requests that have completed
        var cpu_name=this.innerHTML;
        ...
        ).done(function() {
            fill_sum = fill_sum+parseFloat(fill_percent);
            numDoneRequests++;

            if(numDoneRequests === totalCpus) {
                total_percent = fill_sum/<?php echo $num_rows_cpu; ?>;

                $("canvas[name='master_gauge']").each(function(){
                    var ctx = this.getContext('2d');
                    ...
                    DrawGauge(ctx, w, h, total_percent);
                });
        ...
    alert(fill_sum);
}, 100);

And fear @alfasin's friend, little Bobby Tables. When you do

$sql= mysql_query("SELECT used FROM tbl_cpu_use WHERE cpu_name='$cpu_name' ORDER BY id DESC LIMIT 1;");
                                                                ^^^^^^^^^

you're inserting the user's input, completely unchecked, into a query that is going to you're database and opening yourself up to SQL injection. I realize this might be a contrived example, and if it is, I apologize for pointing out something you already know.

(also, please check out "Why shouldn't I use mysql_* functions in PHP?" for reasons you shouldn't be using the mysql_ library to connect to your database AND for some nifty alternatives)

Community
  • 1
  • 1
  • Thanks, this provided the solution. It started working right sporatically, and I realized the counting function solution when it started working as the total gauge would flicker due to the asynchronous behavior of the post. But I found I didn't need the counter and the only thing I had to move to done was this line "total_percent = fill_sum/;"... and your right, I got a lot of work ahead of me to switch to mysqli, escape string checking, and similar things like the modern version of session coding. Thanks! – gunslingor Sep 13 '15 at 20:16