Tuesday, 20 December 2011

PHP Ajax Simple Programming

First We will build a simple ajax library. Then, write a page to load the ajax library. This is very basic application. You can still extend it for more complex web.
Ok, for this practice, we need 3 file (I create within www/test/ajax directory):
  1. ajax.js -> as ajax library
  2. test.php -> as main page
  3. home.html -> will be loaded as content
First, write below line codes within ajax.js

function callAJAX(url, pageElement, callMessage) {
          document.getElementById(pageElement).innerHTML = callMessage;
          try {
            req = new XMLHttpRequest(); /* e.g. Firefox */
          } catch(e) {
              try {
              req = new ActiveXObject("Msxml2.XMLHTTP");
       /* some versions IE */
              } catch (e) {
                  try {
                  req = new ActiveXObject("Microsoft.XMLHTTP");
      /* some versions IE */
                  } catch (E) {
                     req = false;
                  }
              }
          }
        req.onreadystatechange = function() {responseAJAX(pageElement);};
        req.open("GET",url,true);
          req.send(null);
   
      }
   
    function responseAJAX(pageElement) {
        var output = '';
        if(req.readyState == 4) {
             if(req.status == 200) {
                  output = req.responseText;
                  document.getElementById(pageElement).innerHTML = output;
                }
           }
       }

*-------------------**-------------**--------------**--------------------------*

then, we create test.php, enter following codes:

<html>
<head>
 <SCRIPT language="JavaScript" SRC="ajax.js"></SCRIPT>
</head>
<body onload="callAJAX('home.html','displaydiv')">
<table>
<tr>
<td id="displaydiv"></td>
</tr>
</table>
</body>
</html>
 
 *-------------------**-------------**--------------**--------------------------*
 
 last, we create home.html, enter following line code: 
 
front page test
 
Now, point your browser to http://localhost/test/ajax/test.php, you will get the output.

No comments:

Post a Comment

Visual comparison of the two methods, creating a simple table.

Option 1, using PHP: // PHP $html = '<table>' ;     foreach ( $data as $row ) {     $html .= '<tr>...