1

I have a javascript function named table() in a seperate file called "table.js". It basically gets 3 array arguments and sorts them, then fills the HTML table with sorted values.

The problem is: 3 array arguments are in PHP and they are PHP array variables. How can I: Call the table function with these php array variables like:

table($name,$grade,$grade2)

2 Answers 2

1
 var name = "<?php echo $name; ?>";
 var grade1= "<?php echo $grade1; ?>";
 var grade2= "<?php echo $grade2; ?>";


table(name,grade1,grade2);
0

Simply like this:

<script>

var name = [<?php echo '"' . implode('","', $name) . '"'; ?>];
var grade1 = [<?php echo '"' . implode('","', $grade1) . '"'; ?>];
var grade2 = [<?php echo '"' . implode('","', $grade2) . '"'; ?>];

table(name, grade1, grade2);

</script>
8
  • And what should my javascript function be? It is currently like: function table(name,grade1,grade2) Is it okay? Commented Feb 12, 2014 at 1:31
  • @user3179249 that should be okay, yes. Commented Feb 12, 2014 at 1:32
  • @user3179249 see my updated answer, please. I just realized you can't just echo an array, plus arrays in PHP look a bit different from arrays in JS. The code in my updated answer should work though. Commented Feb 12, 2014 at 1:35
  • Alright, and i added <script src="table.js"></script> to the start of the <body> of the HTML. So if i call the function within the php, it will be same as manually writing the arrays on top of javascript code like: names=["adam","daniel] grades1=[50,100] right? Commented Feb 12, 2014 at 1:36
  • @user3179249 For example <?php echo json_encode($name); ?> will become: ['adam', 'daniel']. Commented Feb 12, 2014 at 1:37

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.