PHP JS

PASS VARIABLES BETWEEN PHP & JAVASCRIPT

(quick examples)

PHP VARIABLE <?php $pv = "Foo"; ?>

PHP ECHO JS CODE

01

ECHO JAVASCRIPT CODE <?php echo "var jv = '$pv';"; ?>

SHORT ECHO TAG TO “INSERT VALUE” var jv = "<?=$pv?>";

INSERT INTO HTML FORM <input type="text" id="txt"  value="<?=$pv?>">

INSERT INTO HTML FORM

02

PHP VARIABLE <?php $pv = "Foo"; ?>

JS GET FIELD VALUE var jv = document.getElementById("txt") .value;

JSON TO PASS ARRAY

03

PHP CONVERT ARRAY TO STRING <?php $pv = json_encode(["A", "B", "C"]); ?>

JAVASCRIPT CONVERT STRING TO ARRAY var jv = JSON.parse('<?=$pv?>');  

JS AJAX FETCH DATA FROM PHP fetch("SCRIPT.PHP") .then(res => res.text()) .then(data => { console.log(data); });

AJAX FETCH DATA

04

PHP OUTPUT VALUE $pv = "Foo"; echo $pv;  

PHP JSON OUTPUT echo json_encode(["A", "B", "C"]]);

AJAX FETCH JSON ARRAY

05

JS AJAX FETCH DATA FROM PHP fetch("SCRIPT.PHP") .then(res => res.text()) .then(data => { console.log(data); });