Scripting Languages CS5142, Fall 2013 hw07


Concept Questions

hw07_1 AJAX

1a.
(3 points) Which of the three basic features of AJAX (Asynchronous, JavaScript, XML) is missing from the AJAX example in the lecture?
1b.
(3 points) What is the advantage of using the HTTP GET method in AJAX, as opposed to the HTTP POST method?
1c.
(4 points) In AJAX, the client asynchronously requests more information from the server. Why can't the server just send all the necessary information up-front when the client first loads the page?

hw07_2 Databases

Consider the following UML class diagram.
2a.
(5 points) Design relations (database tables) for classes Restaurant and Cuisine and their association. You can make the simplifying assumption that all attributes are strings.
2b.
(5 points) Design relations (database tables) for the rest of the class diagram. Again, assume all attributes are strings.

Programming exercises

hw07_3 AJAX

(10 points) Consider the AJAX application from the lecture slides from 10/18/2013, repeated here for your convenience.

a.html
<html><head>
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <script src="c.js"></script>
</head><body bgColor="#00ff00">
  Time: <span id="time">(please click button)</span>
  <form name="in">
    <input type="button" value="Toggle Color" onclick="localChange();">
    <input type="button" value="Request Time" onclick="sendRequest();">
  </form>
</body></html>
b.php
<?php sleep(3); echo date('h:i:s') ?>
c.js
function localChange() {
  var blue = document.bgColor == '#0000ff'
  document.bgColor = blue ? '#00ff00' : '#0000ff';
}
function sendRequest() {
  document.getElementById('time').innerHTML = '(please wait)';
  var xhr = false;
  function handleResponse() {
    if (4 == xhr.readyState && 200 == xhr.status)
      document.getElementById('time').innerHTML = xhr.responseText;
  }
  try { xhr = new XMLHttpRequest(); } catch(e1) {
    try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e2) {
      try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e3) {
        alert('Could not create XMLHttpRequest object.'); } } }
  xhr.open('GET', 'b.php?nonce=' + Math.random(), true);
  xhr.onreadystatechange = handleResponse;
  xhr.send(null);
}
3a.
(3 points) Install these scripts on your own web page on the class web server. When you submit this homework, please indicate the URL at which the script is running, as well as the htaccess user name and password if necessary.
3b.
(7 points) Change the application so that instead of getting the time from the server, it reads a string from the user, sends it to the server in an AJAX call, the server converts it to upper case, and the response handler displays it. Please include the source code for your answers in the plain-text file with your solutions ot the remaining questions. Below is a snapshot of what your application should look like.

hw07_4 Databases

(10 points) Consider the following PHP code.
<html><head>
  <title>Calorie Tracker</title>
</head><body>
  <!-- open database, and create tables if they do not yet exist -->
  <?php
    $verbose = false;
    //TODO (a) modify the following line to use a path in your home directory
    $db = new PDO("sqlite:<your_home_directory>/data/hw07.db");
    $tableExists = ("integer" == gettype($db->exec("SELECT count(*) FROM CurrentTotal"))) ? true : false;
    if (!$tableExists) {
      if ($verbose) echo "Table 'CurrentTotal' does not yet exist, creating it ...<br/>";
      $db->exec("CREATE TABLE CurrentTotal(User VARCHAR(50), Total INTEGER)");
      $db->exec("INSERT INTO CurrentTotal VALUES('me', 0)");
    } else {
      if ($verbose) echo "Reopened table 'CurrentTotal'<br/>";
    }
    $tableExists = ("integer" == gettype($db->exec("SELECT count(*) FROM DishCalories"))) ? true : false;
    if (!$tableExists) {
      if ($verbose) echo "Table 'DishCalories' does not yet exist, creating it ...<br/>";
      $db->exec("CREATE TABLE DishCalories(Dish VARCHAR(50), Calories INTEGER)");
      $initInfo = array("apple, medium" => 60, "rice, cup" => 242);
      foreach ($initInfo as $dish => $cal) {
        $db->exec("INSERT INTO DishCalories VALUES('" . addslashes($dish) . "', " . $cal . ")");
      }
    } else {
      if ($verbose) echo "Reopened table 'DishCalories'<br/>";
    }
  ?>
  <!-- process input, if any -->
  <?php
    if (array_key_exists("action", $_POST)) {
      if ("Track" == $_POST["action"]) {
        if ($_POST["trackDish"]) {
          if ($verbose) echo "Action Track(" . $_POST["trackDish"] . ")<br/>\n";
          //TODO (b) write your code here: increase the total calories by the calories for the dish
        }
      } elseif ("Clear" == $_POST["action"]) {
        if ($verbose) echo "Action Clear<br/>\n";
        $db->exec("UPDATE CurrentTotal SET Total = '0' WHERE User='me'");
      } elseif ("Insert" == $_POST["action"]) {
        if ($_POST["insertDish"] && $_POST["insertCalories"]) {
          if ($verbose) echo "Action Insert(" . $_POST["insertDish"] . ", " . $_POST["insertCalories"] . ")<br/>\n";
          //TODO (c) write your code here: insert the dish and calories into table DishCalories
        }
      }
    }
  ?>
  <hr/>
  <!-- show previous output for user input -->
  Current total:
  <?php
    foreach ($db->query("SELECT Total FROM CurrentTotal WHERE User='me'") as $row) {
      echo $row["Total"];
    }
  ?>
  calories<br/>
  <hr/>
  <!-- show form for user input -->
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method=post>
    <table border=0>
      <tr>
        <td><input type="radio" name="action" value="Track" checked /></td>
        <td>Track</td>
        <td>(Dish
          <select name="trackDish">
            <?php
              foreach ($db->query("SELECT Dish FROM DishCalories ORDER BY Dish") as $row) {
                echo "<option>" . $row["Dish"] . "</option>";
              }
            ?>
          </select>)</td></tr>
      <tr>
        <td><input type="radio" name="action" value="Clear" /></td>
        <td>Clear</td>
        <td>(Current total)</td></tr>
      <tr>
        <td><input type="radio" name="action" value="Insert" /></td>
        <td>Insert</td>
        <td>(Dish <input type="text" name="insertDish" /></td></tr>
      <tr>
        <td/>
        <td/>
        <td>&rarr; Calories
            <input type="text" name="insertCalories" size="5" />)</td></tr>
    </table>
    <input type="submit" value="submit" />
  </form>
</body></html>
4a.
(3 points) Install these scripts on your own web page on the course web server. Also, fill in the missing database directory at TODO (a). For example, if you user name is me, the directory is /home/me/data. You need to create that directory and set its permissions to rwxrwxrwx for the script to work. When you submit this homework, please indicate the URL at which the script is running. I recommend that you password-protect it, so please include the htaccess user name and password as well.
4b.
(4 points) Write the missing code at TODO (b) for tracking calories for a dish.
4b.
(3 points) Write the missing code at TODO (c) for inserting a new mapping from a dish to its calories.

Please include the source code for your answers to question 4 in the plain-text file with your solutions ot the remaining questions.

The above code is sufficient for this homework. However, if you have time and interest, you could also make various extensions to this script. For example, you could support different users, or you could maintain historical information by dates. If you are not very interested in nutrition, you could track something else, such as exercise. If you own a cell-phone with a web browser, I recommend that you also take a look at your solution from there.


http://www.cs.cornell.edu/Courses/cs5142/2013fa/hw07.html