I want to call the array from php file to javascript file

javascript
#1

I want to call the array in php file to javascript file

I did this code but didn’t retrieve the array and there is no error shows:

in data.php:


        <?php 


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

        ?>

and in script.js:

function drawLineColors() {

        var data = new google.visualization.DataTable();
		data.addColumn('string', 'time');
       data.addColumn('number', 'Temperature');
       data.addColumn('number', 'Humidity');
	   
	    $.get('data.php').then(function(data2){
			
			
		data.addRows([
		
		[data2],
		
		]);

any help please , thanks for all

#2

Hi,

You should just be able to do:

<?php 
  echo "<script> // Your JS here </script>"
?>

And be able to have your second script refer to whatever was output by the PHP.

If that’s not working, inspect your page source to find out what is being rendered.


That said, if you find yourself doing this more than very occasionally, I’d look at ways to better structure your code. For example, you could make an Ajax request to a PHP endpoint to grab the data you need for your chart.

1 Like
#3

Hi James thanks for your reply :slight_smile:

you mean that I put my script.js code inside php file?

Sorry if I am misunderstood because I am still new with php and javascript and learning

#4

Well you could do that, I guess.

However, I’d rather assumed you had a PHP file which included a script tag, kinda like:

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>
  <body>
    <!-- Wonderful content here -->

    <script src="index.js"></script>
  </body>
</html>

And what you could do is echo any data you need to the PHP page before including the script tag.

    <!-- Wonderful content here -->

    <script><?php echo "var a = 100;"; ?></script>
    <script src="index.js"></script>
  </body>
</html>

That way, anything you echo from PHP will be available in script.js.

#5

I have index.php which I want to call a script.js which script.js can call the array in data.php file …Idon’t know if I made it complicated!

index.php:

  <head>
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<script src="jquery-3.4.1.js"></script>
<script type="text/javascript">

 setInterval(function () { $.get("tempr.php", function(temp) {
  $(".TempStatus").html(temp + " &deg;C");
})}, 3000);
</script>
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-material-design.min.css">
<link rel="stylesheet" href="css/ripples.min.css">
<script src="js/bootstrap.min.js"></script>
<script src="js/material.min.js"></script>
<script src="js/ripples.min.js"></script>
<!-- Animate.css -->
<link rel="stylesheet" href="css/animate.min.css">

    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="script.js"></script>

data.php:

<?php 
$servername = "localhost";
     $database = "user";
     $username = "user";
     $password = "1234";
$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 
 $data2 = array(); 
 if ($result->num_rows > 0) { 
 while ($row = $result->fetch_assoc()) { 
 array_push($data2, [$row['time'], $row['temp'], $row['hum']]); 
 }
 }
 echo json_encode($data2); 
 ?>

and script.js:

 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');
	   
	    $.get('data.php').then(function(data2){	
		data.addRows([data2]);

	let rowIndex = data.getNumberOfRows() - 1; //gets the row index of last row
    let lastTime = data.getValue(rowIndex, 0); //gets the first column
    let lastTemp = data.getValue(rowIndex, 1); //gets second column
    let lastHum = data.getValue(rowIndex,2); //gets third column
#7

First, does your query return any data? Test it directly in the browser to see if it is working correctly.

Second, add some debugging to your calling code using something like console.log so that you can see what is happening. Does it even call the PHP code to retrieve the data? Do you need to tell your code that the data coming back is in JSON format?

#8

Yes when I debug it with console.log(data2) inside data.addRows can fetch the array:

[["2019-05-13 00:25:13","27.20","41.00"],["2019-05-13 00:26:00","27.20","41.00"],["2019-05-13 01:26:03","28.10","39.00"],["2019-05-13 02:56:11","28.40","37.00"],["2019-05-13 03:26:15","28.40","37.00"],["2019-05-13 03:56:21","28.40","37.00"]]
#9

Then you’ve gotten the data.

if data2 is already an array, why are you wrapping it in an array wrapper?

1 Like
#10

So you mean I dont have to add data3 between [ ] ?

#11

Yes I got the data with console.log but don’t know how to reflected under addRows!

#12

I’ve read in one place that you might need to do something like this:

$.get('data.php').then(function(data2){	
  var obj = JSON.parse(data2);
  data.addRows(obj);

but there’s also a suggestion that date format can be an issue. https://groups.google.com/forum/#!topic/google-visualization-api/Om0d76wrFGg

1 Like
#13

$.get has optional parameters, such that you can define the return type specifically.

$.get("data.php","json");
I wouldn’t use .then on a request that may eventually require large loads, because it can trigger when the server sends a ‘in progress’ notification; instead look for .done

1 Like
#14

It was really the JSON.parse I was adding there. I’m not really clued up on Ajax, there seems to be many ways to achieve the same thing - which isn’t necessarily a bad thing, of course.

#15

OK now I got something and I think i am close :kissing_smiling_eyes:

I did this:
script.js:

var jsonData = $.ajax({
        url: "data.php",
        dataType: "json",
        async: false
    }).responseText;

    var obj = JSON.parse(jsonData);
	
	console.log(obj)
    data.addRows(obj);

data.php:


 <?php 
 $data = array(); 
 if ($result->num_rows > 0) { 
 while ($row = $result->fetch_assoc()) { 
 array_push($data, [$row['time'], $row['temp'], $row['hum']]); 
 }
 }
 echo json_encode($data); 
 ?>

but gave me: error Type mismatch. Value 27.20 does not match type number in column index 1

that’s because i choose column 1 and 2 to be a number not a string !

how can I make the array output to be as a number in data.php file?

#16

Yes thanks for all I gottcha! I added (int) before $row and I got it as integer !

but the number become fixed like 24 and the real is 24.5 can I make it as real?

#17

Solved with floatval in php