PHP JS

PASS VARIABLES BETWEEN PHP & JAVASCRIPT

PHP VARIABLE <?php $PHPVAR = "Bar"; ?>    PHP ECHO JS CODE <script><?php echo "var JSVAR = '$PHPVAR';"; ?></script>

PHP ECHO JS CODE

01

PHP VARIABLE <?php $PHPVAR = "Bar"; ?>    PHP SHORT TAG <script> var JSVAR = "<?=$PHPVAR?>"; </script>

PHP SHORT TAG WEAVE

02

JAVASCRIPT AJAX FETCH fetch("SCRIPT.PHP") .then(result => result.text()) .then((data) => { console.log(data); });

PHP SIMPLE OUTPUT $PHPVAR = "FOO BAR!"; echo $PHPVAR;

AJAX FETCH DATA

03

JSON ENCODE ARRAY TO STRING <?php $PHPVAR = ["One", "Two", "Three"]; $PHPVAR = json_encode($PHPVAR);  ?>

JSON PASS ARRAY

04

JSON DECODE STRING TO ARRAY <script>  var JSVAR = '<?=$PHPVAR?>';  JSVAR = JSON.parse(JSVAR);  </script>

PHP JSON OUTPUT $PHPVAR = ["FOO", "BAR"]; echo json_encode($PHPVAR);

AJAX FETCH JSON ARRAY

05

JAVASCRIPT AJAX FETCH fetch("SCRIPT.PHP") .then(result => result.json()) .then((data) => { console.log(data); });