PHP and AJAX.

PHP and AJAX
2005 will definitely be remembered as the rise of AJAX – the new development technique that many believe will blur the line between web-based and desktop applications. This acronym is a label for the rich, highly responsive and interactive interfaces of AJAX-enabled applications. It stands for “Asynchronous JavaScript + XML”.
AJAX is a development technique that utilizes in a unique way a number of already mature technologies: HTML/XHTML, XML, DHTML, the XmlHttpRequest object, and JavaScript.
The AJAX technique was first used after Microsoft implemented Microsoft.XMLHTTP COM object that was part of The Microsoft XML Parser distributive. As an ActiveX object in Internet Explorer 5, it was used to create the famous Outlook Web Access. It is also used in many of the Google applications, including the Calendar and Google Mail. Other labels for the same technology as AJAX are Load on Demand, Asynchronous Requests, Callbacks, and Out-of-band Calls.
The core idea behind AJAX is to make the communication with the server asynchronous, so that data is transferred and processed in the background. As a result the user can continue working on the other parts of the page without interruption. In an AJAX-enabled application only the relevant page elements are updated, only when this is necessary.


  1. Initial request by the browser – the user requests the particular URL.
  2. The complete page is rendered by the server (along with the JavaScript AJAX engine) and sent to the client (HTML, CSS, JavaScript AJAX engine).
  3. All subsequent requests to the server are initiated as function calls to the JavaScript engine.
  4. The JavaScript engine then makes an XmlHttpRequest to the server.
  5. The server processes the request and sends a response in XML format to the client (XML document). It contains the data only of the page elements that need to be changed. In most cases this data comprises just a fraction of the total page markup.
  6. The AJAX engine processes the server response, updates the relevant page content or performs another operation with the new data received from the server. (HTML + CSS)
Example showing AJAX in action: http://www.telerik.com/demos/aspnet/grid/examples/ajax/virtualscrollpaging/defaultcs.aspx
A simple AJAX example using PHP for the backend script:
<html><head><title>Test of Ajax Form Processing</title></head>
<body>
<script type="text/javascript">
<!--
// Routine to blend together the browser differences for
//   accessing id fields on a page
function getObject(id) { ///////////////////////////////////
  var elm = null;
  if (document.getElementById) elm = document.getElementById(id);
  else if (document.layers) elm = document.layers[id];
  else if (document.all) elm = document.all[id];
  return elm;
} // end getObject

var req; // request object used by loadXMLDocGET and loadXMLDocPOST


// AJAX routine to get GET data for a form
function loadXMLDocGET(url,action) { /////////////////////////////
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
    req.onreadystatechange = processReqChange;
    req.open("GET", url, true);
    req.send(null);
    }
  else if (window.ActiveXObject) {
    // branch for IE/Windows ActiveX version
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange = processReqChange;
      req.open("GET", url, true);
      req.send();
      }
  }
} // end loadXMLDocGET


// AJAX routine to get POST data for a form
function loadXMLDocPOST(url,data) { //////////////////////////////
  /// alert (data);
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
    req.overrideMimeType('text/html');
    req.onreadystatechange = processReqChange;
    req.open("POST", url, true);
    req.setRequestHeader("Content-Type",
           "application/x-www-form-urlencoded; charset=UTF-8");
    req.setRequestHeader("Content-length", data.length);
    req.setRequestHeader("Connection", "close");
    req.send(data);
    }
  elseif (window.ActiveXObject) {
    // branch for IE/Windows ActiveX version
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange = processReqChange;
      req.open("POST", url, true);
      req.setRequestHeader("Content-Type",
           "application/x-www-form-urlencoded; charset=UTF-8");
      req.setRequestHeader("Content-length", data.length);
      req.setRequestHeader("Connection", "close");
      req.send(data);
      }
  }
} // end loadXMLDocPOST


function processReqChange() { ////////////////////////////////
  if (req.readyState == 4) { // only if req shows "complete"
    if (req.status == 200) { // only if "OK"
      /// alert (req.responseText);
      var output = document.getElementById('output');
      output.innerHTML = req.responseText;
      }
    else alert("There was a problem retrieving the data:\n"
              + req.statusText);
    }
} // end processReqChange



// Get all the fields on the specified form and place them
//   in a URL-encoded format that is suitable for the
//   AJAX POST call
function getFormValues(fobj,submitButtonName) { ////////////
  var str = '';
  for (var i=0; i &ly; fobj.elements.length; i++) {
    /// alert (fobj.elements[i].type);
    switch(fobj.elements[i].type) {
      case 'text' :
      case 'textarea' :
      case 'password' :
        if (!fobj.elements[i].disabled) str +=
           fobj.elements[i].name + '=' +
           encodeURIComponent(fobj.elements[i].value) + '&';
        break;
      case 'button' :
      case 'submit' :
        if (fobj.elements[i].name == submitButtonName)
          str += fobj.elements[i].name + '=' +
             encodeURIComponent(fobj.elements[i].value) + '&';
        break;
      case 'hidden' :  //hidden cannot be disabled
        str += fobj.elements[i].name + '=' +
           encodeURIComponent(fobj.elements[i].value) + '&';
        break;
      case 'checkbox':
      case 'radio':
        if (fobj.elements[i].checked &&
                   !fobj.elements[i].disabled)
          str += fobj.elements[i].name + '=' +
            encodeURIComponent(fobj.elements[i].value) + '&';
        break;
      case 'select-one':
        var index = fobj.elements[i].selectedIndex;
        if (!fobj.elements[i].disabled) {
          var opt = fobj.elements[i].options[fobj.elements[i].
                 selectedIndex],
              value = opt.value;
          // This test is required because IE apparently doesn't
          //   use the .value field; it uses .text instead :(
          if (!value || !('value' in opt)) value = opt.text;
          str += fobj.elements[i].name + '=' +
                      encodeURIComponent(value) + '&';
          }
        break;
      case 'select-multiple':
        if (!fobj.elements[i].disabled) {
          for (var j = 0; j < fobj.elements[i].length; j++) {
            var optElem = fobj.elements[i].options[j];
            if (optElem.selected == true) {
              var value = optElem.value;
              // This test is required because IE apparently
              //   doesn't use the .value field; it uses .text
              //   instead :(
              if (!value || !('value' in optElem))
                 value = optElem.text;
              str += fobj.elements[i].name + '[]=' +
                 encodeURIComponent(value) + '&';
              }
            }
          }
        break;
      } // end switch
    } // end for

  str = str.substr(0,(str.length-1));  // strip final &
  return str;
} // end getFormValues



function sendForm(form,submitButtonName) { ///////////////////
  loadXMLDocPOST(
    'http://students.cse.unt.edu/~donrclass/ajax/postTest.cgi',
    getFormValues(form,submitButtonName));
} // end sendForm

function sendGet() {
  loadXMLDocGET(
     'http://students.cse.unt.edu/~donrclass/ajax/postTest.cgi' +
         '?test=123&sample=data&something=else');
} // end sendGet

-->
</script>


<h2>Test of POST form submission using AJAX</h2>

<form>
Your Name: <input type="text" id="text" name="name"
   value="Fred Jones">  

Your Address: <input type="text" name="address"
   value="This & that."><br />

Sex: Male <input type=radio name="Sex" value="Male">
  Female <input type=radio name="Sex" value="Female">  

Do this again? <input type=checkbox name="Again" value="1">
<br /><br />

Select The Product Catalog you Want to Receive:
<select id="info" name="Catalog">
<option>Full Product Catalog</option>
<option>Spring Catalog</option>
<option>Special Order Service</option>
</select>
<br /><br />

Multi-Select:<br />
<select name="Multi[]" multiple size=5>
<option>Dallas</option>
<option selected>Houston</option>
<option selected>San Antonio</option>
<option>New York</option>
<option>Los Angeles</option>
<option>San Francisco</option>
</select>  

<textarea name="FullAddress[test]" rows=5 cols=40>
This is a test.
And so is this.
This has < and > in it.
</textarea><br /><br />

<input name="DoIt" type="button" value="Request Information"
   onClick="sendForm(this.form,'DoIt');">
</form>

<p><a href="#" onClick="sendGet();">Send call from
anchor (GET)</a></p>

</body></html>
PHP Script that is called by the AJAX-enabled webpage:
#!/usr/local/bin/php &lt;?php echo '&lt;pre&gt;_POST = ' . print_r ($_POST,true) . "&lt;/pre&gt;\n"; echo '&lt;pre&gt;_GET = ' . print_r ($_GET,true) . "&lt;/pre&gt;\n"; echo '&lt;pre&gt;_FILES = ' . print_r ($_FILES,true) . "&lt;/pre&gt;\n"; ?&gt;


Share on Google Plus

About M

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment