This tutorial shows you how to execute JavaScript code loaded via AJAX into the web page.
For example, we can have a web page with an Ajax code that accesses a PHP script which returns one or more JavaScript scripts (in <script> tags), and we want to execute into the web page the JavaScript code received in the Ajax response, from PHP.
We can do that with the eval() function.
But first we must get the JS code of each <script> element received via Ajax from PHP, and then eval it.
Looking on the net for various ways to get the code of multiple <script> tags added in a string, I found a function (named parseScript) that strips out <script> tags, adds their code in an Array, then eval it.
// this function create an Array that contains the JS code of every <script> tag in parameter // then apply the eval() to execute the code in every script collected function parseScript(strcode) { var scripts = new Array(); // Array which will store the script's code // Strip out tags while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) { var s = strcode.indexOf("<script"); var s_e = strcode.indexOf(">", s); var e = strcode.indexOf("</script", s); var e_e = strcode.indexOf(">", e); // Add to scripts array scripts.push(strcode.substring(s_e+1, e)); // Strip from strcode strcode = strcode.substring(0, s) + strcode.substring(e_e+1); } // Loop through every script collected and eval it for(var i=0; i<scripts.length; i++) { try { eval(scripts[i]); } catch(ex) { // do what you want here when a script fails } } }- This function can be used to execute the JavaScript code received in the Ajax response.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="ro"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-2" /> <title>Ajax tutorial - https://coursesweb.net</title> <script type="text/javascript"><!-- /* - https://coursesweb.net/ajax/ */ // sends data to a php file, via POST, and displays the received answer function ajaxrequest(php_file, tagID) { var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); // XMLHttpRequest object var the_data = ''; // here you can set data to be send to the server (pairs index=value) request.open("POST", php_file, true); // set the request // adds a header to tell the PHP script to recognize the data as is sent via POST request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); request.send(the_data); // calls the send() method with data as parameter // Check request status // If the response is received completely, will be transferred to the HTML tag with tagID request.onreadystatechange = function() { if (request.readyState == 4) { var resp = request.responseText; // get the response from php document.getElementById(tagID).innerHTML = resp; // add the response into the tag with the ID from "tagID" // calls the parseScript() function, with the response from PHP as argument parseScript(resp); } } } // this function create an Array that contains the JS code of every <script> tag in parameter // then apply the eval() to execute the code in every script collected function parseScript(strcode) { /* www.webdeveloper.com */ var scripts = new Array(); // Array which will store the script's code // Strip out tags while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) { var s = strcode.indexOf("<script"); var s_e = strcode.indexOf(">", s); var e = strcode.indexOf("</script", s); var e_e = strcode.indexOf(">", e); // Add to scripts array scripts.push(strcode.substring(s_e+1, e)); // Strip from strcode strcode = strcode.substring(0, s) + strcode.substring(e_e+1); } // Loop through every script collected and eval it for(var i=0; i<scripts.length; i++) { try { eval(scripts[i]); } catch(ex) { // do what you want here when a script fails } } } --></script> </head> <body> <div id="context"> </div> <h4 style="cursor:pointer;" onclick="ajaxrequest('script.php', 'context')"><u>Test</u></h4> </body> </html>
<?php // return some text within html code echo '<b>Text added with Ajax</b>, <i>received from PHP.</i>'; // return the first JS code, which displays an Alert with the current Timestamp echo '<script type="text/javascript"> var tmp = '. time().'; alert("Server Timestamp: "+ tmp); </script>'; // Outputs a second JS script, with another alert window echo '<script type="text/javascript"> alert("The alert from the second JS script from PHP"); </script>'; ?>
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net