Chained Select Menu issue - AJAX


I am currently using the following script to run a PHP script when a dropdown menu option is selected.
This then returns the results from a SQL query and places it in a 2nd dropdown.

However, I would also like to run a script when the web page initially loads.

This basically means I hope my select menu (“2nd dropdown”) will be populated with the results of the PHP script when the page loads. And the user can then filter the results down by using the first dropdown menu.

// Have a function run after the page loads:
window.onload = init;

/* ------------------------------------------------------------------------
 * Can I run this...
 *'get', 'dept_results_ajax.php');
 * ... as soon as my page loads and return the results?
 *  ------------------------------------------------------------------------

// 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:
      $('#did').change(function() {

        // Call the PHP script.
        // Use the GET method.
        // Pass the department_id in the URL.

        // Get the department_id:
        var did = document.getElementById('did').value;

        // Open the connection:'get', 'dept_results_ajax.php?did=' + encodeURIComponent(did));

        // Function that handles the response:
        ajax.onreadystatechange = function() {
          // Pass it this request object:

        // Send the request:

        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) ) {

      // Put the received response in the DOM:
      var results = document.getElementById('results');
      results.innerHTML = ajax.responseText;

      // Make the results box visible: = 'block';

    } else { // Bad status code, submit the form.

  } // End of readyState IF.

} // End of handleResponse() function.

Many thanks for any pointers here.

You can add a callback to the handleResponse function:

function handleResponse(ajax, callback) {

So that you can pass in a function that will be run once the response has been successfully handled.