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 adds an image in web page?
<div> <img> <span>
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which of these CSS codes displays the text oblique?
font-style: italic; text-decoration: underline; font-weight: 500;
#id {
  font-style: italic;
}
Click on the jQuery function used to hide with animation a HTML element.
click() hide() show()
$(document).ready(function() {
  $(".a_class").click(function(){ $(this).hide("slow"); });
});
Click on the correctly defined function in PHP.
fname function() {} function fname() {} function $fname() {};
function fname($a, $b) {
  echo $a * $b;
}
Execute JavaScript scripts loaded via AJAX

Last accessed pages

  1. Dynamic variables in JavaScript (18733)
  2. ActionScript 3 - Change MovieClip Color (8940)
  3. Keep the first Nr IMG tags, Strip all the others (303)
  4. Ajax request when the page is closed (182)
  5. Update and Delete in MySQL Table (1518)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (320)
  2. Read Excel file data in PHP - PhpExcelReader (117)
  3. The Four Agreements (96)
  4. PHP Unzipper - Extract Zip, Rar Archives (91)
  5. The Mastery of Love (85)
Chat
Chat or leave a message for the other users
Full screenInchide