Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Php Arrays to External Javascript File

I've seen some of the questions about the passing PHP arrays to an external JavaScript file, but I can't understand it. I know how to pass PHP arrays to internal JavaScript files but not how to pass them to external JavaScript files.

Coding

   <?php 
      $a = array("Apple","Orange","Grape");
   ?> 

  <script type="text/javascript">
      var jArray= <?php echo json_encode($a); ?>;
      for(var i=0;i<3;i++){
          alert(jArray[i]);
      } 
like image 300
Vji Avatar asked Jan 10 '23 02:01

Vji


2 Answers

use this code, JS File (test.js)

for(var i=0;i<jArray.length;i++){
alert(jArray[i]);
}

PHP File (test.php)

<?php 
      $a = array("Apple","Orange","Grape");
?>
<script type="text/javascript">var jArray =<?php echo json_encode($a); ?>;</script>
<script type="text/javascript" src="test.js"></script>
like image 195
Afzal Ahmad Avatar answered Jan 18 '23 14:01

Afzal Ahmad


You cant use php code directly in your external js file, the given code is,

    <?php 
          $a = array("Apple","Orange","Grape");
    ?> 

  <script type="text/javascript">
      var jArray= <?php echo json_encode($a); ?>;
      for(var i=0;i<3;i++){
          alert(jArray[i]);
      } 
  </script>

I think you can change the code as, 

   //Declaring the array in php 
   <?php 
      $a = array("Apple","Orange","Grape");
   ?> 

  //Assigning the json encoded format to javascript
  <script type="text/javascript">
      var jArray= <?php echo json_encode($a); ?>;  
  </script>

  //You can use the jArray in the external js file 
  <script type="text/javascript" src="externaljsfile.js" >
like image 39
Vivek Prabhakar Avatar answered Jan 18 '23 14:01

Vivek Prabhakar