Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
Christopher Bergin

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:
          handleResponse(ajax);
        }
 
        // Assemble all the form data:
        var fields = ['first_name', 'last_name', 'email', 'department_id',
'phone_ext];
        for (var i = 0; i < fields.length; i++) {
          fields = fields + '=' +
encodeURIComponent(document.getElementById(fields).value);
        }
        var values = fields.join('&');
 
        // Set the request headers:
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        
        // Send the request along with the data:
        ajax.send(values);
      
        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.
      document.getElementById('emp_form').submit();
    }
    
  } // End of readyState IF.
  
} // End of handleResponse() function.

 

 

 

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

XML isn't exactly "legacy", but I would say that JSON is the new, popular kid on the block, as it's more compact than XML and far easier to deal with in JS, which is the client language these days and always one of the two sides of Ajax.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...