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 attribute specifies the HTTP method (GET, POST) used to submit the form-data?
action method value
<form action="script.php" method="post"> ... </form>
Which CSS property allows to add shadow to boxes?
background-image box-shadow border-radius
#id {
  background-color: #bbfeda;
  box-shadow: 11px 11px 5px #7878da;
}
Which function removes the first element from an array?
pop() push() shift()
var fruits = ["apple", "apricot", "banana"];
fruits.shift();
alert(fruits.length);           // 2
Indicate the function that can be used to check if a PHP extension is instaled.
function() filetype() extension_loaded()
if(extension_loaded("PDO") === true) echo "PDO is available."
Execute JavaScript scripts loaded via AJAX

Last accessed pages

  1. Creating XML data - E4X in ActionScript 3 (3087)
  2. The Fifth Agreement (19059)
  3. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141365)
  4. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (26304)
  5. Ajax-PHP Chat Script (49457)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (89)
  2. CSS cursor property - Custom Cursors (18)
  3. CSS3 2D transforms (17)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (12)
  5. The Mastery of Love (11)