0

I want to use PHP variable in .JS file. When I am declare JAVASCRIPT variable with store PHP VARIABLE VALUE, it gives me error of

  1. Expected an identifier and instead saw '<'
  2. Expected an operator and instead saw '?'
  3. Missing ";" before statement
  4. Missing semicolon
  5. Expected an identifier and instead saw '>'
  6. Expected ':' and instead saw ';';

and when I store data with inverted comma then

code:

$disabledDates = <?PHP echo $json_array?>;
console.log($disabledDates);

Then it prints <?PHP echo $json_array?> not an array value; please can help me with it. How can I use it to store PHP variable.

duncan
  • 31,401
  • 13
  • 78
  • 99
hemu
  • 1
  • rename the file .php – Lawrence Cherone Jun 05 '21 at 10:00
  • You might want to check out this solution. https://stackoverflow.com/questions/23740548/how-do-i-pass-variables-and-data-from-php-to-javascript – Osawere Jun 05 '21 at 10:13
  • How can I use this – hemu Jun 05 '21 at 10:21
  • You can set the variable in the PHP file before you include the js-file that needs it. Another alternative would be to make an ajax request in your js file to get the data from a PHP file (this is the preferred option). PHP and JS lives in two different environments. .js files are simply downloaded "as is" and then executed on the client side (the browser), while PHP is being executed on the server. – M. Eriksson Jun 05 '21 at 10:37

1 Answers1

0

You can use a hidden input

html and php code:

<input type="hidden" id="json_array" value="<?=$json_array?>" />

js code

$disabledDates = document.getElementById("json_array").value;
console.log($disabledDates);

this if the data is single like a number or string, if is it an array change the input value to

<input type="hidden" id="json_array" value="<?=implode(',', $json_array);>" />
Samad
  • 34
  • 1
  • 6