PHP JS

HOW TO MAKE AJAX CALLS TO PHP

(simple examples)

HTML WRAPPER <div id="demo"></div>

AJAX GET CONTENT (JS)

01

AJAX FETCH CONTENT fetch("SCRIPT.PHP") .then(res=>res.text()) .then(txt =>    document.getElementById("demo")   .innerHTML = txt; );

OUTPUT DUMMY CONTENT echo "<strong>IT WORKS!</strong>";

AJAX GET CONTENT (PHP)

01

AJAX SUBMIT FORM (JS)

02

HTML FORM <form id="form" onsubmit="return demo()">   <input type="text" name="N" value="V">   <input type="submit" value="GO!"> </form>

AJAX SUBMIT FORM function demo () {   var data = new FormData     (document.getElementById("form"));   fetch("SCRIPT.PHP",      { method:"POST", body:data })   .then(res => res.text())   .then(txt => console.log(txt));   return false; }

AJAX SUBMIT FORM (PHP)

02

PROCESS SUBMITTED FORM print_r($_POST); $sql = "INSERT INTO TABLE...";

AJAX SEND JSON DATA (JS)

03

FORM DATA var data = new FormData(); data.append("DATA",    JSON.stringify(["FOO", "BAR"]));

SEND JSON ENCODED STRING fetch("SERVER.PHP",   { method:"POST", body:data }) .then(res => res.text()) .then(txt => console.log(txt));

AJAX SEND JSON DATA (PHP)

03

JSON DECODE $data = json_decode($_POST["DATA"]); print_r($data);

AJAX GET JSON DATA (JS)

04

FETCH - DECODE JSON fetch("SCRIPT.PHP") .then(res => res.json()) .then(data => console.log(data)); 

AJAX GET JSON DATA (PHP)

04

OUTPUT JSON ENCODED echo json_encode(["FOO", "BAR"]);