0

I have two files. One is a php with mysql connection. If I open manually with my browser I see the right values. For example: [["4","5.000"],["5","1.000"]]

The code:

$query = "SELECT id, wert FROM stat_cpu ORDER BY id LIMIT 100";
$result = mysql_query($query,$db);

    while($row = mysql_fetch_assoc($result))
    {
        $dataset1[] = array($row['id'],$row['wert']);
    }

echo json_encode($dataset1);

I want to show the data in a plot. If I put the values manually in the js all work good. But how can I put it automaticall from the php to the js file?

I have tried this:

...
$.ajax({                                      
url: 'cpudaten.php',
dataType: 'json',  
success: function(data)
{
var cpudaten = data[0];
}});

var updateInterval = 30;
var plot_statistics = $.plot($("#load_statistics"), 
[cpudaten], {....
TrivoXx
  • 161
  • 3
  • 17
  • `cpudaten` is only accessible within the scope of `success`, but even if you make it global it won't work because AJAX is asynchronous. Check this question http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – elclanrs Jul 21 '13 at 10:29
  • Ok thanks for your answer. cpudaten is only a variable. What I must change to get it work. I only want to get the datas from my mysql into the js script. There must be a solution.... – TrivoXx Jul 21 '13 at 10:33
  • Yes, the answers to the question above have the solution. The solution is run your logic _inside_ the callback or use promises. – elclanrs Jul 21 '13 at 10:38
  • Ok I think I am to stupid to understand it :-) Please help me a little bit to understand it. – TrivoXx Jul 21 '13 at 10:53
  • Must I do it so? $(function cpudata(){ $.ajax({ url: 'cpudaten.php', dataType: 'json', success: function(cpudata) { var cpudaten = data[0]; }});}); – TrivoXx Jul 21 '13 at 11:00

1 Answers1

0

You have to put your logic into the success scope. This way.

var plot_statistics;


success: function(data)
{
  var cpudaten = data[0];

  plot_statistics = $.plot($("#load_statistics"), 
                       [cpudaten()], {...}
                      )

}
nicolascolman
  • 549
  • 4
  • 15