Jump to content
Larry Ullman's Book Forums

Chapter 5 Questions And Comments

Recommended Posts

I was having a difficult time getting the script to work. The error I was receiving on Firefox was:





message[0] is undefined   results.innerHTML = message[0].firstChild.nodeValue; 


The error appearing on Safari was more stringent with the initialization of the message variable but citing the same result. The message variable was receiving a value of undefined. Which led me to wonder if the PHP script was returning a value. When printing the value of the data variable, the value was null. When I changed the value of data from responseXML to responseText and printed it out, it provided me with additional information that indicated a database issue. Which leads me to my first question, is there a suggested way to test a PHP script while it is attached to an Ajax script? Printing the values of PHP variables doesn't seem to work since all output must get sent to the Ajax script. Also, does it matter in the script where the handleResponse function is called? It would seem to me that sending data to the PHP script via ajax.send(values) instruction would precede a call to check the response status. Anyway, all set here. On another note, is XML technology still widely used?


// add_employee.js

/*  This page does all the magic for applying
 *  Ajax to an "add an employee" form.
 *  The form data is sent to a PHP 
 *  script using the POST method.
 *  The PHP script sends back a response in XML format.
// Have a function run after the page loads:
window.onload = init;
// Function that adds the Ajax layer:
function init() {
  // Get an XMLHttpRequest object:
  var ajax = getXMLHttpRequestObject();
  // Attach the function call to the form submission, if supported:
  if (ajax) {
    // Check for DOM support:
    if (document.getElementById('results')) {
      // Add an onsubmit event handler to the form:
      document.getElementById('emp_form').onsubmit = function() {
        // Call the PHP script.
        // Use the POST method.
        // Open the connection:
        ajax.open('post', 'add_employee_xml.php');
        // Function that handles the response:
        ajax.onreadystatechange = function() {
          // Pass it this request object:
        // Assemble all the form data:
        var fields = ['first_name', 'last_name', 'email', 'department_id',
        for (var i = 0; i < fields.length; i++) {
          fields = fields + '=' +
        var values = fields.join('&');
        // Set the request headers:
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        // Send the request along with the data:
        return false; // So form isn't submitted.
      } // End of anonymous function.
    } // End of DOM check.
  } // End of ajax IF.
} // End of init() function.
// Function that handles the response from the PHP script:
function handleResponse(ajax) {
  // Check that the transaction is complete:
  if (ajax.readyState == 4) {
    // Check for a valid HTTP status code:
    if ((ajax.status == 200) || (ajax.status == 304) ) {
      var results = document.getElementById('results');
      // Reset all the labels:
      document.getElementById('first_name_label').className = 'title';
      document.getElementById('last_name_label').className = 'title';
      document.getElementById('email_label').className = 'title';
      document.getElementById('department_id_label').className = 'title';
      document.getElementById('phone_ext_label').className = 'title';
      // Get the XML data:
      var data = ajax.responseXML;
      // Get the main response:
      var message = data.getElementsByTagName('result');
      // Get all the errors:
      var errors = data.getElementsByTagName('error');
      // Temp variable to use in the loop:
      var temp = false;
      // Loop through each error:
      for (var i = 0; i < errors.length; i++) {
        // Get the error value:
        temp = errors.firstChild.nodeValue;
        // Change the class:
        document.getElementById(temp + '_label').className = 'error';
      } // End of FOR loop.
      // Put the received response in the DOM:
      results.innerHTML = message[0].firstChild.nodeValue;
      // Make the results box visible:
      results.style.display = 'block';
    } else { // Bad status code, submit the form.
  } // End of readyState IF.
} // End of handleResponse() function.




Link to comment
Share on other sites

Lots of questions.

Here are my basic answers:


1) I almost always put alert(ajax.responseText); within the handle-response function while I'm writing the PHP server-side logic. As you commented, by alerting the responseText property, you can view what's being returned from the PHP script (including potential errors).


2) As long as the handleResponse function is within a scope that the Ajax object can access, anywhere in fine. In other words, the handleResponse function should be defined either in the global context or within a function the Ajax object is accessible in.


3) You should always define the event handler (i.e., onreadystatechange) before the send method is called. In most cases, it won't make a difference, but you never know, and it's best to have the event handler set up and listening for a response before you send the request.


4) In regards to whether XML technology is still widely used or not, that's pretty hard to answer. I will say though that probably the most common method for sending and receiving data these days in JS is JSON format. Look into the JSON.parse and JSON.stringify methods for more info. Do note though that the JSON predefined object is not available in older browsers (e.g., IE6-7).


I personally prefer sending strings of custom-defined formats for Ajax responses, but that's just me. If your entire system is already using XML, then XML is probably a logical choice for the response format.

  • Upvote 1
Link to comment
Share on other sites


  • Create New...