<html>
<head>
<title>JSONP - SQL Web Server Call</title>
<style>
    table  {border:solid black 1px; background-color:#dddddd}
    th     {background-color:#aaaaaa}
    th, td {border-right:solid black 1px; border-bottom:solid black 1px}    
</style>
<!-- <script src=json2.js></script>           // no longer needed -->
</head>
<body>
<h1>JSONP - Web Service Call</h1>
<label for=sql>Enter SQL Statement</label>
<input type=text id=sql size=50 value='show tables' onchange=request()>
<input type=button value='Execute' onClick=request()>
    
See..
<input type=checkbox id=req> <label for=req> request </label>
<input type=checkbox id=resp><label for=resp>response</label>
<hr>

<script>
function request()
{
    url      = "https://workshop.sps.nyu.edu/~sultans/php/demo/ws/jsonpSQL.php";      
    stmt     = document.getElementById('sql').value;
    callback = "parseResponse";
    full_url = url + "?sql=" + stmt + "&callback=" + callback;

    if (document.getElementById('req').checked)
        alert("REQUEST:\n" + full_url);

    head   = document.getElementsByTagName('head')[0]; 
    script = document.createElement('script');
    script.src   = full_url;
    script.async = true;
    head.appendChild(script);
}

function parseResponse(response)
{
      str = JSON.stringify(response,null,'    ');			//stringify and add space for readability
      str = callback +'( '+ str +' )';                                  //add the callback function which is lost due to evaluation

    if (document.getElementById('resp').checked)
        alert("RESPONSE:\n" + str);

    var output_str = "<table>";

    for (var i=0; i<response.length; i++)			//loop thru the outer array
    {
        object = response[i];			

        output_str += "<tr>";

        if (i==0)						//for object 1, print the headers
        {
            output_str += "<tr>";
            for (key in object)					//loop thru first inner objects
                output_str += "<th>" + key + "</th>";
            output_str += "</tr>";
        }
        
        for (key in object)					//loop thru each inner objects
            output_str += "<td>" + object[key] + "</td>";

        output_str += "</tr>";
    }      
    output_str += "</table>";

    document.getElementById('output').innerHTML = output_str;
}
</script>
<div id=output></div>
</body>
</html>