Ajax Course

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.


- Here's the code of the parseScript() function:
// 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.

Here's a complete example. A html page with a button that executes an Ajax script that accesses a PHP file (named "script.php") which returns some text and two separated JavaScript codes (in two <script> tags) that display 2 Alert windows. Then, we add the response from Ajax into a DIV in the html page, and pass the response to the parseScrript() function, which will eval and execute the JavaScript codes received from PHP.
See also the comments in code.
- You can use a PHP file that returns a JS script in a single <script> tag, in this example we use two <script> tags to demonstrate how it works.

Code for the html page with the Ajax script

<!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>

Code for script.php file

<?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>';
?>

This example will show the following result, click on the "Test" button:

Test

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Execute JavaScript scripts loaded via AJAX

Last accessed pages

  1. Ajax-PHP Rating Stars Script (16816)
  2. Zodiac Signs JavaScript code (11162)
  3. MouseEvent - Events for Mouse (2910)
  4. PHP getElementById and getElementsByTagName (49442)
  5. Viewing the Flash Window (2936)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (473)
  2. CSS cursor property - Custom Cursors (80)
  3. The Mastery of Love (70)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)