+ 9
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request. An example (using traditional event registration model for simplicity): <!-- headers etc. omitted --> <script> function callPHP(params) { var httpc = new XMLHttpRequest(); // simplified for clarity var url = "get_data.php"; httpc.open("POST", url, true); // sending as POST httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1) httpc.onreadystatechange = function() { //Call a function when the state changes. if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors alert(httpc.responseText); // some processing here, or whatever you want to do with the response } } httpc.send(params); } </script> <a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a> <!-- rest of document omitted --> Whatever get_data.phpproduces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader :) @Sololearn
22nd Dec 2017, 12:13 PM
James16
James16 - avatar