Very basic AJAX and PHP example for interactively loading select html elements and drop down boxes with XML content

by Klaus Graefensteiner 20. September 2010 22:42

Introduction

In this very basic example I am demonstrating how to interactively load Html Select elements aka drop down boxes with AJAX and PHP. After a user logs in successfully the first select element provides the user with options for a car make. Based on this first selection a second select element gets rendered to further narrow the search by specifying the car model.

image

Figure 1: Login, Select make and Select model

Video

This little video clip shows the script in action.

HTML and JavaScript – AJAX

This example doesn’t use a JavaScript library or framework. It is coded to the “Browser” metal.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Select Your Car</title>
  <script type="text/javascript">


  function validateLogon(dataSource, divID)
  {
    var user_name = document.getElementById('user_name').value
    var password = document.getElementById('password').value

    var data = user_name + "|" + password;

    getXML(dataSource, divID, data);
    return false;
	
  }

  function getModelInfo()
  {
    var data = document.getElementById("car_make_selection").value; 
    var dataSource = 'get_cars.php';
    var divID = "car_model_div";
    if (data != '-')
    {
      getXML(dataSource, divID, data);
    }
  }

  function getCarInfo()
  {
	  var model = document.getElementById("car_model_selection").value;
	  var make = document.getElementById("car_make_selection").value;
	  alert("You selected " + make + " " + model);
  }

  function displayXML(XML, divID)
  {
    //alert("displayXML");
    var logonXMLElements = XML.getElementsByTagName("logon");
    var logonResult = logonXMLElements[0].firstChild.data;
    var resultDiv = document.getElementById(divID);
    var resultHtml ="";
    if(logonResult.toLowerCase() == "success")
    {
      resultHtml = '<h1>Select a car make!</h1>';
      categoryXMLElements = XML.getElementsByTagName("make");
      var length = categoryXMLElements.length;

      var i = 0;

      resultHtml += '<select id="car_make_selection" onchange="getModelInfo();">';
      resultHtml += '<option value="-">-</option>'
		   
      for(i=0;i < length; i++)
      {
        var option = categoryXMLElements[i].firstChild.data;
        resultHtml += '<option value="';
        resultHtml += option;
        resultHtml += '">';
        resultHtml += option;
        resultHtml += '</option>';
      }
      resultHtml += '</select>';
      resultDiv.innerHTML = resultHtml;

      formDiv = document.getElementById("logonDiv");
      formDiv.style.visibility = "hidden";

      resultDiv.style.position = "absolute";
      resultDiv.style.top = "10px";

    }
    else if(logonResult.toLowerCase() == "model")
    {
      modelXMLElements = XML.getElementsByTagName("model");
      var length = modelXMLElements.length;

      var i = 0;

      resultHtml += '<h1>Select a car model!</h1>';
      resultHtml += '<select id="car_model_selection" onchange="getCarInfo();">';
       
      for(i=0;i < length; i++)
      {
        var option = modelXMLElements[i].firstChild.data;
        resultHtml += '<option value="';
        resultHtml += option;
        resultHtml += '">';
        resultHtml += option;
        resultHtml += '</option>';
      }
      resultHtml += '</select>';
      resultDiv.innerHTML = resultHtml;
      
    }
    else
    {
      resultDiv.innerHTML = '<h1 style="color: red;">Login Failed! Please try again or call the help desk!</h1>';
    }
  }


  function getXML(dataSource, divID, data) 
  { 

    var XMLHttpRequestObject = false; 

    if (window.XMLHttpRequest) 
    {
      XMLHttpRequestObject = new XMLHttpRequest();
      XMLHttpRequestObject.overrideMimeType("text/xml");
    } 
    else if (window.ActiveXObject) 
    {
      XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
    }
	  
    if(XMLHttpRequestObject) 
    {
      var obj = document.getElementById(divID);

      obj.innerHTML = "Loading from " + dataSource;

		        
      XMLHttpRequestObject.open("POST", dataSource); 
      XMLHttpRequestObject.setRequestHeader('Content-Type', 
        'application/x-www-form-urlencoded'); 

      XMLHttpRequestObject.onreadystatechange = function() 
      { 
        if (XMLHttpRequestObject.readyState == 4 && 
          XMLHttpRequestObject.status == 200) 
        {
           var myXML = XMLHttpRequestObject.responseXML;
           displayXML(myXML, divID);
        } 
      }

      XMLHttpRequestObject.send("data=" + data);
    }
    return false;
  }

  </script>
</head>
<body>
<div id="logonDiv">
<h2>Logon To This Site!</h2>
<form action="select_your_car.html" name="logonForm">
<table>
  <tr>
    <td>
      User name:
    </td>
    <td>
      <input id="user_name" name="user_name" type="text" />
    </td>
  </tr>
    <tr>
    <td>
      Password:
    </td>
    <td>
      <input id="password" name="password" type="password" />
    </td>
  </tr>
  <tr>
    <td>
      &nbsp;
    </td>
    <td>
      <br /><input id="logon" type="submit" value="Logon to Site" onclick="return validateLogon('validate_logon_make.php', 'loginResultDiv')" />
    </td>
  </tr>
</table>
</form>
</div>
<div id="loginResultDiv">
</div>
<div id="car_model_div">
</div>
</body>
</html>

The JavaScript is inline with the html, but for better readability I added it here again with the JavaScript Syntax Highlighter Brush:

  function validateLogon(dataSource, divID)
  {
    var user_name = document.getElementById('user_name').value
    var password = document.getElementById('password').value

    var data = user_name + "|" + password;

    getXML(dataSource, divID, data);
    return false;
	
  }

  function getModelInfo()
  {
    var data = document.getElementById("car_make_selection").value; 
    var dataSource = 'get_cars.php';
    var divID = "car_model_div";
    if (data != '-')
    {
      getXML(dataSource, divID, data);
    }
  }

  function getCarInfo()
  {
	  var model = document.getElementById("car_model_selection").value;
	  var make = document.getElementById("car_make_selection").value;
	  alert("You selected " + make + " " + model);
  }

  function displayXML(XML, divID)
  {
    //alert("displayXML");
    var logonXMLElements = XML.getElementsByTagName("logon");
    var logonResult = logonXMLElements[0].firstChild.data;
    var resultDiv = document.getElementById(divID);
    var resultHtml ="";
    if(logonResult.toLowerCase() == "success")
    {
      resultHtml = '<h1>Select a car make!</h1>';
      categoryXMLElements = XML.getElementsByTagName("make");
      var length = categoryXMLElements.length;

      var i = 0;

      resultHtml += '<select id="car_make_selection" onchange="getModelInfo();">';
      resultHtml += '<option value="-">-</option>'
		   
      for(i=0;i < length; i++)
      {
        var option = categoryXMLElements[i].firstChild.data;
        resultHtml += '<option value="';
        resultHtml += option;
        resultHtml += '">';
        resultHtml += option;
        resultHtml += '</option>';
      }
      resultHtml += '</select>';
      resultDiv.innerHTML = resultHtml;

      formDiv = document.getElementById("logonDiv");
      formDiv.style.visibility = "hidden";

      resultDiv.style.position = "absolute";
      resultDiv.style.top = "10px";

    }
    else if(logonResult.toLowerCase() == "model")
    {
      modelXMLElements = XML.getElementsByTagName("model");
      var length = modelXMLElements.length;

      var i = 0;

      resultHtml += '<h1>Select a car model!</h1>';
      resultHtml += '<select id="car_model_selection" onchange="getCarInfo();">';
       
      for(i=0;i < length; i++)
      {
        var option = modelXMLElements[i].firstChild.data;
        resultHtml += '<option value="';
        resultHtml += option;
        resultHtml += '">';
        resultHtml += option;
        resultHtml += '</option>';
      }
      resultHtml += '</select>';
      resultDiv.innerHTML = resultHtml;
      
    }
    else
    {
      resultDiv.innerHTML = '<h1 style="color: red;">Login Failed! Please try again or call the help desk!</h1>';
    }
  }


  function getXML(dataSource, divID, data) 
  { 

    var XMLHttpRequestObject = false; 

    if (window.XMLHttpRequest) 
    {
      XMLHttpRequestObject = new XMLHttpRequest();
      XMLHttpRequestObject.overrideMimeType("text/xml");
    } 
    else if (window.ActiveXObject) 
    {
      XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
    }
	  
    if(XMLHttpRequestObject) 
    {
      var obj = document.getElementById(divID);

      obj.innerHTML = "Loading from " + dataSource;

		        
      XMLHttpRequestObject.open("POST", dataSource); 
      XMLHttpRequestObject.setRequestHeader('Content-Type', 
        'application/x-www-form-urlencoded'); 

      XMLHttpRequestObject.onreadystatechange = function() 
      { 
        if (XMLHttpRequestObject.readyState == 4 && 
          XMLHttpRequestObject.status == 200) 
        {
           var myXML = XMLHttpRequestObject.responseXML;
           displayXML(myXML, divID);
        } 
      }

      XMLHttpRequestObject.send("data=" + data);
    }
    return false;
  }

Login PHP

This script takes care of the user login.

<?php
  $data = $_POST['data'];
  #echo "You entered >$data<";
  if($data == 'KlausG|pAsSwoort7')
  {
    echo '<?xml version = "1.0" ?>';
    echo '<cars_selection>';
    echo '<logon>Success</logon>';
    echo '<car_makes>';
    echo '<make>Ford</make>';
    echo '<make>Honda</make>';
    echo '<make>Audi</make>';
    echo '</car_makes>';
    echo '</cars_selection>';
  }
  else
  {
    echo '<?xml version = "1.0" ?>';
    echo '<cars_selection>';
    echo '<logon>Error</logon>';
    echo '</cars_selection>';
  }
?>

Get Cars PHP

This script sends XML files for the car makes and then for a car makes model. Very basic like I mentioned earlier.

<?php
  $data = $_POST['data'];
  #echo "You entered >$data<";
  if($data == 'Ford')
  {
    echo '<?xml version = "1.0" ?>';
    echo '<cars_selection>';
    echo '<logon>Model</logon>';
    echo '<model>F150</model>';
    echo '<model>Explorer</model>';
    echo '<model>F250</model>';
    echo '</cars_selection>';
  }
  else if ($data == 'Honda')
  {
    echo '<?xml version = "1.0" ?>';
    echo '<cars_selection>';
    echo '<logon>Model</logon>';
    echo '<model>Accord</model>';
    echo '<model>Odyssey</model>';
    echo '<model>Civic</model>';
    echo '</cars_selection>';
  }
  else if ($data == 'Audi')
  {
    echo '<?xml version = "1.0" ?>';
    echo '<cars_selection>';
    echo '<logon>Model</logon>';
    echo '<model>A4</model>';
    echo '<model>A6</model>';
    echo '<model>A8</model>';
    echo '</cars_selection>';
  }
  else
  {
    echo '<?xml version = "1.0" ?>';
    echo '<cars_selection>';
    echo '<logon>Error</logon>';
    echo '</cars_selection>';
  }
?>

Download

This little AJAX application can be downloaded here: AjaxDropDownBoxesSelectACar.zip

Make sure that the php files and the html are in the same directory.

Ausblick

This example doesn’t explicitly worry about caching requests in the browser. This is something that I am going to figure out next.

Tags: , , , , , , , , ,

AJAX | Php | XML

About Klaus Graefensteiner

I like the programming of machines.

Add to Google Reader or Homepage

LinkedIn FacebookTwitter View Klaus Graefensteiner's profile on Technorati
Klaus Graefensteiner

Klaus Graefensteiner
works as Developer In Test and is founder of the PowerShell Unit Testing Framework PSUnit. More...

Open Source Projects

PSUnit is a Unit Testing framwork for PowerShell. It is designed for simplicity and hosted by Codeplex.
BlogShell is The tool for lazy developers who like to automate the composition of blog content during the writing of a blog post. It is hosted by CodePlex.

Administration

About

Powered by:
BlogEngine.Net
Version: 1.6.1.0

License:
Creative Commons License

Copyright:
© Copyright 2014, Klaus Graefensteiner.

Disclaimer:
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Theme design:
This blog theme was designed and is copyrighted 2014 by Klaus Graefensteiner

Rendertime:
Page rendered at 7/31/2014 10:33:51 AM (PST Pacific Standard Time UTC DST -7)