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 in <table> to create table header cell?
<thead> <th> <td>
<table><tr>
  <th>Title 1</th>
  <th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin
.some_class {
  line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()
document.getElementById("id_button").onclick = function(){
  window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()
$ar_dir = scandir("dir_name");
var_export($ar_dir);
Execute JavaScript scripts loaded via AJAX

Last accessed pages

  1. PHP Method Chaining (5464)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142541)
  3. Insert, Select and Update NULL value in MySQL (59194)
  4. Line and Text (1347)
  5. Validate radio and checkbox buttons (10078)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (544)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (63)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)