-1

I googled about it and didn't find an solution, can you help me with this issue?

I have a javascript variable that is the name of a php session address, and I want to use this session value in my javascript code, but I don't know how to pass this name to the php and return the session value to my js code.

I'm using the session to set values of my dynamic form fields. So I use

var field_name = "field";    
document.getElementById(field_name).value = "<?php if(isset($_SESSION['field_name'])) echo $_SESSION['field_name'];?>";

The field ID have the same name of the session address. I can't simply use the word "field" because it's dynamic.

I thank you in advance.

  • 10
    Possible duplicate of [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – laurent Feb 03 '17 at 15:09

2 Answers2

0

Just use:

var info= <?php echo json_encode("some_php_variable_here", JSON_HEX_TAG); ?>;
michaelitoh
  • 2,317
  • 14
  • 26
0

This is probably only with a data attribute in the HTML. In the JS code one should definitely (actually never) run PHP code.

The data attributes can then be filled with PHP and read out in the JS.

Daniel
  • 126
  • 2
  • 5