Get echo from php into javascript (separate files)

786

I have been searching for hours and can't put this to work...

This is my first website, I have a Google gauge that need to ask a database for the value that it should put on the gauge. I know how to ask the database and how to update the gauge, the problem is how should I pass the echo variable from the php file to the javascript file. (The php code need to be in a separate file or otherwise the google gauges won't display).

You can check a actual version of the website here (At the moment the gauges are static).

PHP code:

<?php
    $DB_NAME = 'TSB';
    $DB_HOST = 'db.tecnico.ulisboa.pt';
    $DB_USER = 'xxxxxxxxx';
    $DB_PASS = 'xxxxxxxxx';
    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS);
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    $mysqli->query('USE xxxxxxxxxxx;');
    $result = $mysqli->query('SELECT SOC FROM TSB ORDER By time DESC LIMIT 1;');
    $row = $result->fetch_array();
    $soc = $row['SOC'];
    echo $soc;
?>

The output of the echo is an int, or at least came as one from the database.

What I'm trying in the javascript file:

function SOC() {
  var data = google.visualization.arrayToDataTable([
    ['Label', 'Value'],
    ['SOC', 0]
  ]);
  var options = {
    width: 250, height: 250,
    redFrom: 0, redTo: 10,
    yellowFrom: 10, yellowTo: 25,
    minorTicks: 5,
    majorTicks: ['0','25','50','75','100']
  };
  var formatter = new google.visualization.NumberFormat({
    suffix: '%',
    fractionDigits: 0
  });
  formatter.format(data, 1);
  var chart = new google.visualization.Gauge(document.getElementById('SOC'));

  chart.draw(data, options);
  setInterval(function() {
    var socPHP;
    $.ajax({
        url: 'soc.php',
        type: 'get',
        dataType:'text',
        // I don't know how to properly put the $soc from php in a javascript variable
    });
    data.setValue(0, 1, 100); // 100 should be replaced by the value 
    //that came from the php file and the variable should be an INT
    chart.draw( data, options);
  }, 3000);
}

UPDATE After Tina Suggestion:

<?php
  $DB_NAME = 'TSB';
    $DB_HOST = 'db.tecnico.ulisboa.pt';
    $DB_USER = 'xxxxx';
    $DB_PASS = 'xxxxx';
    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS);
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    $mysqli->query('USE xxxxxx;');
    $result = $mysqli->query('SELECT SOC FROM TSB ORDER By time DESC LIMIT 1;');
    $row = $result->fetch_array();
    $soc = $row['SOC'];
?>;

function SOC() {
  var data = google.visualization.arrayToDataTable([
    ['Label', 'Value'],
    ['SOC', 0]
  ]);
  var options = {
    width: 250, height: 250,
    redFrom: 0, redTo: 10,
    yellowFrom: 10, yellowTo: 25,
    minorTicks: 5,
    majorTicks: ['0','25','50','75','100']
  };
  var formatter = new google.visualization.NumberFormat({
    suffix: '%',
    fractionDigits: 0
  });
  formatter.format(data, 1);
  var chart = new google.visualization.Gauge(document.getElementById('SOC'));

  chart.draw(data, options);
  setInterval(function() {
    data.setValue(0, 1, <?php echo $soc; ?>);
    chart.draw( data, options);
  }, 3000);
}
790

Answer

Solution:

Take a look at the documentation that comes with the gauges, the data needs to be in the format: [label, value]

One way of achieving your goal is after you've sent your ajax request, you need to build an array in your php script and then use the json_encode function to output the data. You'll also need to add the parameterdataType: 'JSON' to your ajax request.

EDIT: Its frustrating reading all the comments and seeing you not get anywhere so I wrote the following which you should be able to adapt.

You need 2 files: a HTML or PHP file containing your HTML and JS, the second needs to be a PHP file containing your database query.

File 1:

<html>
  <head>
   <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
   <script type="text/javascript">
      google.charts.load('current', {'packages':['gauge']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Label', 'Value'],
          ['Memory', 80],
          ['CPU', 55],
          ['Network', 68]
        ]);

        var options = {
          width: 400, height: 120,
          redFrom: 90, redTo: 100,
          yellowFrom:75, yellowTo: 90,
          minorTicks: 5
        };

        var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

        chart.draw(data, options);

        setInterval(function() {
            $.ajax({
                url: "g.php",
                dataType: "JSON",
                data:{},
                success: function(x){
                  data.setValue(0, 1, x["key"]);
                  chart.draw(data, options);
                }
            });
        }, 2000);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" class="page_speed_1506061465"></div>
  </body>
</html>

File 2, g.php (This generates a random number and outputs JSON. You can put your database query here instead of the rand() function):

<?php

    $data = array();

    $data["key"] = rand(0,100);

    print(json_encode($data));

?>

The AJAX query in the first file sends a request to file 2, g.php every 2 seconds and fetches a simple JSON object.

174

Answer

Solution:

If I have understood your question correctly, in your javascript file just add where it's needed, e.g.,

['SOC', <?php echo $soc; ?>]

People are also looking for solutions to the problem: Android Login Using PHP, MySQL and Volley

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.