I'm trying to update a div on my webpage using ajax & perl. This is what I have at the moment and it kind of works.
html
<h2 id="cpu">--</h2>
js/ajax call
$.ajax({
type: 'GET',
url: '/cgi-bin/cpu.pl',
async: true,
success: function(data) {
$('#cpu').html(data);
}
});
perl
#!/usr/bin/perl
# Ref: Calculating CPU Usage from /proc/stat
# (http://colby.id.au/node/39)
use strict;
use warnings 'all';
use utf8;
use List::Util qw(sum);
$| = 1;
my ( $prev_idle, $prev_total ) = qw(0 0);
while () {
open( STAT, '/proc/stat' ) or die "WTF: $!";
while (<STAT>) {
next unless m{^cpu\s+[0-9]+};
my @cpu = split ' ', $_;
shift @cpu;
my $idle = $cpu[3];
my $total = sum(@cpu);
my $diff_idle = $idle - $prev_idle;
my $diff_total = $total - $prev_total;
my $diff_usage = 100 * ( $diff_total - $diff_idle ) / $diff_total;
$prev_idle = $idle;
$prev_total = $total;
print "Content-type: text/html
";
printf "%0.2f%% ", $diff_usage;
}
close STAT;
}
This works partially because it does update the the h2 with a percentage but only once. I did have it where it said sleep 1;
inside the loop and that worked great executing it from the command line but when I used it with ajax and I looked at the network, for cpu.pl it always said status pending and it never changed.
I'm not sure if I'm even going about this the correct way. So any help would be great, thanks.