Skip to content
Advertisement

Calling a php variable in JS does not work

I’m trying to make a user input by reading the contents of my server directory with php. So the user can select a file, in my case a CSV file which gets saved into a variable and then gets processed further down in my JavaScript code that should make a chart from it. All it does now is output the path string of the selected file. I tried using the json_encode function but it still doesn’t seem to work.

<?php
$dir = '/var/www/html/';
$graphen = '';
if (!isset($_POST['submit'])) { 
 if ($dp = opendir($dir)) { 
 $files = array(); 
 while (($file = readdir($dp)) !== false) { 
  if (!is_dir($dir . $file)) { 
  $files[] = $file; 
  } 
 } 
 closedir($dp); 
 } else { 
 exit('Directory not opened.'); 
 } 
 if ($files) { 
 echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">'; 
 foreach ($files as $file) { 
  echo '<input type="checkbox" name="files[]" value="' . $file . '" /> ' . 
   $file . '<br />'; 
 } 
 echo '<input type="submit" name="submit" value="submit" />' . 
  '</form>'; 
 } else { 
 exit('No files found.'); 
 } 
} else { 
 if (isset($_POST['files'])) { 
 foreach ($_POST['files'] as $value) {
  $graphen .= $dir . $value . '<br />';
 } 
 } else { 
 exit('No files selected'); 
 }
} 
echo $graphen;
?>

<!DOCTYPE html> 
<html lang="en">

<head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

   
    <script src="highcharts.js"></script>
    <script src="data.js"></script>
    <script src="exporting.js"></script>
    <script src="export-data.js"></script>
    <script src="accessibility.js"></script>
    <script src="jquery-3.5.1.min.js"></script>


</head>

<body>

    <div id="container1"></div>

    <script type="text/javascript">

    var fileName = <?php echo json_encode($graphen); ?>; //doesn't work
       

            $.ajax({
                type: "GET",
                url: fileName,
                success: function (data) {
                    drawChart(data)
                }
            });


        function drawChart(raw_data) {
          //my code to draw chart is here and working
}

Advertisement

Answer

If you assign a String to a variable in JavaScript, use " or ':

var x = "Hello";

Your current code results in

var fileName = <?php echo json_encode($graphen); ?>; => var fileName = variable;

Add quotes and it should work:

var fileName = '<?php echo json_encode($graphen); ?>'; => var fileName = 'variable';

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement