<!--

ajax10.html

Gets stock quote from quote6.php via Ajax, inserting result into DOM.
Also displays returned JSON in a textarea.

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;
            }

            // get symbol
            var symbol = document.getElementById("symbol").value;

            // construct URL
            var url = "quote6.php?symbol=" + symbol;

            // get quote
            xhr.onreadystatechange =
            function()
            {
                // only handle loaded requests
                if (xhr.readyState == 4)
                {
                    if (xhr.status == 200)
                    {
                        // evaluate JSON
                        var quote = eval("(" + xhr.responseText + ")");

                        // show JSON in textarea
                        document.getElementById("code").value = xhr.responseText;

                        // insert quote into DOM
                        var div = document.createElement("div");
                        var text = document.createTextNode(symbol + ": " + quote.price);
                        div.appendChild(text);
                        document.getElementById("quotes").appendChild(div);
                    }
                    else
                        alert("Error with Ajax call!");
                }
            }
            xhr.open("GET", url, true);
            xhr.send(null);
        }

    </script>
    <title></title>
  </head>
  <body>
    <form onsubmit="quote(); return false;">
      Symbol: <input id="symbol" type="text">
      <br><br>
      <input type="submit" value="Get Quote">
    </form>
    <br><br>
    <div id="quotes"></div>
    <br><br>
    <textarea cols="80" id="code" rows="16"></textarea>
  </body>
</html>