<!--

ajax8.html

Gets stock quote (plus day's low and high) from quote5.php via Ajax,
embedding result in page itself.

David J. Malan
Computer Science S-75
Harvard Summer School

-->

<!DOCTYPE html>

<html>
  <head>
    <script>

        // an XMLHttpRequest
        var xhr = null;

        /*
         * void
         * quote()
         *
         * Gets a quote.
         */
        function quote()
        {
            // instantiate XMLHttpRequest object
            try
            {
                xhr = new XMLHttpRequest();
            }
            catch (e)
            {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }

            // handle old browsers
            if (xhr == null)
            {
                alert("Ajax not supported by your browser!");
                return;
            }

            // construct URL
            var url = "quote5.php?symbol=" + document.getElementById("symbol").value;

            // get quote
            xhr.onreadystatechange = handler;
            xhr.open("GET", url, true);
            xhr.send(null);
        }


        /*
         * void
         * handler()
         *
         * Handles the Ajax response.
         */
        function handler()
        {
            // only handle requests in "loaded" state
            if (xhr.readyState == 4)
            {
                if (xhr.status == 200)
                {
                    // get XML
                    var xml = xhr.responseXML;

                    // update price
                    var prices = xml.getElementsByTagName("price");
                    if (prices.length == 1)
                    {
                        var price = prices[0].firstChild.nodeValue;
                        document.getElementById("price").innerHTML = price;
                    }

                    // update low
                    var lows = xml.getElementsByTagName("low");
                    if (lows.length == 1)
                    {
                        var low = lows[0].firstChild.nodeValue;
                        document.getElementById("low").innerHTML = low;
                    }

                    // update high
                    var highs = xml.getElementsByTagName("high");
                    if (highs.length == 1)
                    {
                        var high = highs[0].firstChild.nodeValue;
                        document.getElementById("high").innerHTML = high;
                    }
                }
                else
                    alert("Error with Ajax call!");
            }
        }

    </script>
    <title></title>
  </head>
  <body>
    <form onsubmit="quote(); return false;">
      Symbol: <input id="symbol" type="text">
      <br><br>
      Price: <span id="price"></span>
      <br>
      Low: <span id="low"></span>
      <br>
      High: <span id="high"></span>
      <br><br>
      <input type="submit" value="Get Quote">
    </form>
  </body>
</html>