Ajax: It's not only code

Ajax works outside the page but safely inside the JavaScript sandbox.

1 2 3 4 5 6 Page 5
Page 5 of 6

The server component of the application is listed in Example 13-2. Typically, this is a database request to look up cities, with more than two states listed. However, in the interest of keeping the example as self-contained as possible, the “cities” are created as a static string, based on the state selected.

Example 13-2. Server component of Ajax application in PHP

<?php

//If no search string is passed, then 
we can't search
if(empty($_GET['state'])) {
    echo "No State Sent";
} else {
    //Remove whitespace from beginning
    & end of passed search.
    $search = trim($_GET['state']);
    switch($search) {
      case "MO" :
         $result = "<option 
            value='St. Louis'>
            St. Louis</option>" .
            "<option 
            value='Kansas City'>
            Kansas City</option>";
         break;
      case "WA" :
         $result = "<option
            value='Seattle'>
            Seattle</option>" .
            "<option 
            value='Spokane'>
            Spokane</option>" .
            "<option 
            value='Olympia'>
            Olympia</option>";
         break;
      case "CA" :
         $result = "<option 
            value='San Francisco'>
            San Francisco</option>" .
            "<option 
            value='Los Angeles'>
            Los Angeles</option>" .
            "<option 
            value='Web 2.0 City'>
            Web 2.0 City</option>" .
            "<option
            value='barcamp'
            >BarCamp</option>";
         break;
      case "ID" :
         $result = "<option 
              value='Boise'>Boise</option>";
         break;
      default :
         $result = "No Cities Found";
         break;
      }
    echo $result;
}
?>

Figure 13-2. Web page after Ajax call

Example 13-2

Example 13-2

Server component of Ajax application in PHP

. . .

1 2 3 4 5 6 Page 5
Page 5 of 6
How to supercharge Slack with ‘action’ apps
  
Shop Tech Products at Amazon