Mark Bean
Mark Bean

Reputation: 111

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

Upvotes: 0

Views: 823

Answers (3)

RRikesh
RRikesh

Reputation: 14381

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>

Upvotes: 0

sejordan
sejordan

Reputation: 321

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.

Upvotes: 0

Dan Kanze
Dan Kanze

Reputation: 18595

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)

Upvotes: 1

Related Questions