0

Let's say I have 100 rows of php-variables that I want to save to javascript variables.

 $data1;
 $data2;
 $data3;
 $data4;
 ...
 $data99;
 $data100;

How can I save those variables in a function so I don't have to save it manually like:

var data1 = '<?php echo $data1; ?>';
...

Would be very great if it can be solved. So much work otherways :/

5 Answers 5

2

pack them into an object, then use

var data = <?php echo json_encode($your_object); ?>;
Sign up to request clarification or add additional context in comments.

1 Comment

How do I do that? Pretty new to this @adassko
2

Doesnt work. PHP is serverside, javascript clientside. When the JS is initialised, PHP is done with its work. But you can either use AJAX or do a for-loop and write the javascript with PHP.

echo "<script>";
for($i = 0; $i < 100; $i++){ 
    echo "var data" . $i " = " . $data1 .";";
}
echo "</script>";

Untested.

6 Comments

This would echo the same variable 100 times.
you probably meant ${'data' . $i'} and for($i = 1; $i <= 100; $i++)
arf, yes, of course, just created a fast code without thinking.^^
will try it :) @YUNOWORK
Is this right? echo "var data" . $i " = " . ${'data' .$i}. "; "; It gives me just errors. @Adassko
|
1

If your variables are like the ones you posted and the number of variables is known you you could simply do:

$num_vars = 50;

for($i=0; $i < 50; $i++) {
   $tmp_var = "$data$i";
   if (is_numeric($tmp_var)) {
      echo "var myVar$i = $tmp_var;\n";
   } else {
      echo "var myVar$i = '$tmp_var';\n";
   }
}

Keep in mind the use of double quotes. PHP recognizes variables in double quotes. Also test if it is a number or a string as shown.

Comments

0

You can store them in an array and then with a php for loop populate a javascript array with the values.

Comments

0

create an array of variables and then try to use json_encode

var data = <?php echo json_encode($data); ?>;
data = JSON.parse(data);
alert(data['data1']);

Comments

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.