0

I have php file which includes arrays and I want to call it from javascript file but I don't know the way

I tried this way but gives me unexpected error:

script.js file:

  google.charts.load('current', {'packages':['corechart', 'line']});
  google.charts.setOnLoadCallback(drawLineColors);
  function drawLineColors() {

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'time');
   data.addColumn('number', 'Temperature');
   data.addColumn('number', 'Humidity');

    data.addRows([  

           <?php include 'data.php' ?>

    ]);

data.php file :

   <?php 
  $servername = "localhost";
 $database = "db";
 $username = "db";
 $password = "124";

 $connect = mysqli_connect($servername, $username, $password, $database);
 if (!$connect) {
  die("Connection failed: " . mysqli_connect_error());
  }
$query = 'SELECT * FROM climate';

$result = mysqli_query($connect, $query);


 ?>

<?php 


        if ($result->num_rows > 0) {
          while ($row = $result->fetch_assoc()) {
          echo "['".$row['time']."',".$row['temp'].",".$row['hum']."],";
           }
        }

      ?>
2
  • You will need to share how you output your values in data.php Commented May 14, 2019 at 10:03
  • @Carlos Alves Jorge yes I edited the question with data,php Commented May 14, 2019 at 10:10

1 Answer 1

1

I am assuming that you want your arrays from 'data.php' file to be pushed into data.addRows.

You can use jQuery AJAX, please find the below snippet :

$.get('data.php',function(arr, status) {
  console.log("YOUR ARRAY HERE", arr);
})

Hope it helps!!!

Sign up to request clarification or add additional context in comments.

4 Comments

I have array in data.php I want to echo it and show it to data.addRows from javascript file
You can use json_encode in data.php to get it in your javascript file. ``` <?php $data = array(); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { array_push($data, [$row['time'], $row['temp'], $row['hum']]); echo "['".$row['time']."',".$row['temp'].",".$row['hum']."],"; } } echo json_encode($data); ?> ```
thanks Kunal , But I am still confused how can I call data.php file in my javascript file
Okay. In your scripts.js file : $.get snippet and in your php file use json_encode

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.