PHP JS

USING JSON IN PHP AND JAVASCRIPT

(quick examples)

PHP JSON ENCODE - ARRAY TO STRING  $str = json_encode(["Red", "Blue"]);

BASIC JSON IN PHP & JS

01

JS JSON STRINGIFY - ARRAY TO STRING var str = JSON.stringify(["Red", "Blue"]); 

PHP JSON DECODE - STRING TO ARRAY $arr = json_decode($str, 1);

JS JSON PARSE - STRING TO ARRAY var arr = JSON.parse(str);

JS - JSON ENCODE ARRAY TO STRING var data = new FormData(); data.append("demo", JSON.stringify(["Red", "Blue"]);

SEND ARRAY FROM JS TO PHP

02

JS - SEND DATA TO SERVER fetch("SERVER.PHP", { method:"POST", body:data });

PHP - JSON DECODE BACK TO ARRAY $color = json_decode($_POST["color"]);

JS - FETCH FROM PHP fetch("SERVER.PHP") .then(res => res.json()) .then(arr => console.log(arr));

JS FETCH ARRAY FROM PHP

03

PHP - OUTPUT IN JSON echo json_encode(["Red, Blue"]);