简体   繁体   中英

Passing a javascript array to php variable on the same PHP file

I have this PHP file wherein I need this javascript variable available (inside the same file) to be pass on my PHP variable, something like this.

myfile.php contais:

    var testing  = ["EWMLMc3ES3I", "RSdKmX2BH7o", "SIXwlxhjaKY", "acp8TbBPVos", "6GpKR4-TLoI", "XLKLkTnKRwg", "6WPELkw5kD0"];

and I want to make it like this

 testing = <?php $new_testing ?>

I need a suggestion maybe a jquery snippet but with something like my scenario which is a javascript in a php file.


edit: additional info, the reason for this is , because there's another javascript codes (not on the same file but rather had it include via external JS) that needs that particular PHP variable. so say here's the logic:

  1. javascript_variable ---> php_variable (passing the javascript variable to php) then,
  2. php_variable --> another_javascript_variable (pass the php to another javascript file)
  3. the another_javascript_variable will the be executed by that external javascript file

It only goes one way for an "on page load event". In other words, JavaScript (client side code) always renders AFTER PHP (server side code).

A way around this is too use an AJAX POST onload where the client side has finished rendering and returns a response back to the server. (Your array)

From the way I understand your question, I believe what you're looking for is the php function json_encode

Then, you can basically do what you are trying.

<?php $new_testing = array('one', 'two', 'three', 'four'); ?>

<script>
    var testing = <?php echo json_encode($new_testing); ?>;
</script>

If you're asking "How can my JavaScript pass a variable to my PHP", the answer is AJAX -- you have to make a whole new request.

On your PHP side, use json_encode() to convert your php array to a suitable format to pass it to the javascript.

PHP:

$var = array( 'lorem', 'ipsum', 'dolor');
$json_var = json_encode($var);
$parameter = array( 'js_var' => $json_var );
wp_enqueue_script('my_script');
wp_localize_script('my_script', 'object_name', $parameter); 

Javscript:

<script>
my_var = jQuery.parseJSON(object_name.js_var);
alert(my_var); 
</script>
<?php
$testing  = ["EWMLMc3ES3I", "RSdKmX2BH7o", "SIXwlxhjaKY", "acp8TbBPVos", "6GpKR4-TLoI", "XLKLkTnKRwg", "6WPELkw5kD0"];

echo 'var testing = ['.$testing[0].', '.$testing[1].' ]';

?>

Echo with php the js code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM