简体   繁体   中英

Having trouble getting a number from an AJAX request to a javascript variable

I'm attempting to make a chart that displays the CPU percentage on a page, and auto-updates along with the CPU percent as it changes. I'm having issues understanding how to get information back from the PHP script once the AJAX request has been sent. Ideally I'd like to be able to use the variable '$cpuPercent' and have in the '.update();' part of my update function.

I've tried having the php code within the update function and echoing the $cpuPercent, but it does not update each time, as it'll only run once, and keep using the same number each time it updates.

Here is the php from my system_actions.php script.

exec('wmic cpu get loadpercentage', $output2);
$cpuPercent = $output2[1];
echo json_encode($cpuPercent);

Here is my javascript

function getUsage(){
    $.ajax({
        url:'system_actions.php?action=cpu',
        async: true,
        dataType: 'json',
        type: 'post',
        success:function(output){
            var cpuPercent = parseInt(output);
            document.getElementById('cpu').value = cpuPercent;
            updateChart();
        }
    })
}
setInterval(getUsage, 2500);

function updateChart(){
    var link = document.getElementById('randombutton');
    link.click();
}

  $('.updatePieCharts').on('click', function(e) {
    e.preventDefault();
    charts.each(function() {
      var number = parseInt(document.getElementById('cpu').value);
      $(this).data('easyPieChart').update(number);
    });
  });

I definitely feel a disconnect in how it all works together, but I can't quite figure it out. Any help or a point in the right direction would be great. Back to google I go.

Since your PHP script is returning JSON, the output variable in your success callback will be either a JavaScript object or array. Either way, you can't really use parseInt on it, so var cpuPercent is probably never getting set to anything useful.

If you post some sample output of your PHP script, we can tell you how to locate the number you're looking for.

Try this.

$.ajax({
    cache: false
})

And also you can try toggling your async option to false too.

I think this flot example may help you. http://www.flotcharts.org/flot/examples/realtime/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM