AntwonA
AntwonA

Reputation: 11

How to Insert PHP SQL Query data into Javascript

#I have built a php app to query a database and return results from a specific row. I now want to post those results into a javascript that produces a graphic. I need help as I am new to both php and javascript. Here is my two source codes together in the same file.

...

<?php
$servername = "#mysever";
$username = "#myusername";
$password = "#mypassword";
$dbname = "#mysqldbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT Zone, Premises, ServiceOrders, Balance FROM wrzones WHERE Zone='WR Zone 8'";

$result = $conn->query($sql);


if ($result->num_rows > 0) {
  echo "<table><tr><th>Zone</th><th>Premises</th><th>ServiceOrders</th><th>Balance</th></tr>";
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "<tr><td>".$row["Zone"]."</td><td>".$row["Premises"]." </td><td>".$row["ServiceOrders"]." </td><td>".$row["Balance"]." </td></tr>";
  }
  echo "</table>";
} else {
  echo "0 results";
}
$conn->close();
?>

...

#The query produces the following output: Zone = WR Zone 1; Premises = 130; Service Orders = 60; Balance = 70;

#Below is the start of the javascript which is provided via canvasjs.com ...

<script>
window.onload = function () {

var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    title:{
        text: "Zone 1 - Fiber Sign-ups", #I want Zone 1 to come from .php output from "Zones"
        horizontalAlign: "center"
    },
    data: [{
        type: "doughnut",
        startAngle: 130, #I want 130 to come from .php output from "Premises"
        //innerRadius: 130,  #I want 130 to come from .php output from "Premises"
        indexLabelFontSize: 17,
        indexLabel: "{label} - #percent%",
        toolTipContent: "<b>{label}:</b> {y} (#percent%)",
        dataPoints: [
            { y: 60, label: "Sign-ups" }, 
            { y: 70, label: "Balance" } 

... #I want 60 to come from .php output from "ServiceOrders" #I want 70 to come from .php output from "Balance" ...

        ]
    }]
});
chart.render();

}
</script>
    
    

... #HTML Output of Chart ...

<div>
   <h2 align="center">City Sites</h1>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
    <script src="canvasjs.min.js">
    </script>
</div>
</div>

#I tried to add the data into the javascript

Upvotes: 0

Views: 900

Answers (1)

Thanasis Balatsoykas
Thanasis Balatsoykas

Reputation: 176

You can use AJAX to communicate between PHP and JAVASCRIPT using an intermediate data type named JSON.

So you basically create an XMLHttpRequest object with which you send a message to your php script to retrieve the data you want.

Here is a resource: AJAX request

And a more specific one for your problem: PHP and AJAX

Upvotes: 1

Related Questions