<!DOCTYPE html>
<html>
<head>
<title>Fetch call</title>
<meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
<style>
    table {border:1px solid black}
    th    {border:1px solid black; background-color:lightgray}
    td    {border:1px solid black}
</style> 
</head>

<body>
    <h1>Search for Student Name: </h1>
  
    <span title="Student lastname or ALL">Search For:</span>
    <input type="text"     id="name" size=46 onKeyUp="doRequest();">
    <input type="checkbox" id="showData"> Show returned Data 
    <input type="radio"    id="JSON" name="type" checked="on" > JSON
    <input type="radio"    id="XML"  name="type"              > XML
    <hr><br>    
    <div id="output"></div>
   
<script>

var url = "https://workshop.sps.nyu.edu/~sultans/php/demo/ws/webFetch.php"    //server process to call                                 

//========================================================================================
// doRequest: process the request each time there is a change in the entry field
//========================================================================================
function doRequest() 
{ 
    searchName = document.getElementById("name").value;          //get value entered in form    

    param = "name=" + searchName;
    
    if (document.getElementById("JSON").checked)                //if JSON is requested
        param += "&format=JSON";
    if (document.getElementById("XML").checked)                 //if XML is requested
        param += "&format=XML";
            
    url_param = url + "?" + param                               //url plus paramaters

    promise = fetch(url_param)                                  //fetch() method retrieves a url, and returns a Promise
    promise.then(doResponse, alertError)                        //promise.then(call_ok_method, call_error_method)                
}

//====================================================================================================
// doResponse: parse returned data and display on html page 
//     The returned string is either 
//         - XML 
//         - JSON string in format: [ {'name':'value', 'name':'value', ...}, {'name':'value', ...} ]
//====================================================================================================
function doResponse(promiseObj)
{
//  alert(promiseObj.status +"-"+ promiseObj.statusText)        //for debugging: Should print 200-OK (or 404-NOT FOUND, or ...)

    anotherPromise = promiseObj.text()                          //text() method retrieves the response body, and returns a Promise
    anotherPromise.then(display, alertError)                    //promise.then(call_ok_method, call_error_method)
}
//====================================================================================================
// display: display the returned data (if good) 
//====================================================================================================
function display(text)
{
    if (document.getElementById("showData").checked)                //if show returned data is requested
        alert(text);                                                //display raw response data 

    if (document.getElementById("XML").checked)                     //if XML is requested
    {                                                               //and create an array        
        text = text.replaceAll('sqlData>','table>');
        text = text.replaceAll('row>','tr>');
        text = text.replaceAll('student_id>', 'td>');
        text = text.replaceAll('lname>', 'td>');
        text = text.replaceAll('fname>', 'td>');
        text = text.replaceAll('ssn>', 'td>');
        text = text.replaceAll('sex>', 'td>');
        text = text.replaceAll('course_id>', 'td>');
        text = text.replaceAll('description>', 'td>');
        text = text.replaceAll('price>', 'td>');
        
        lines = text.replace('<table>',
                             '<table><tr><th>student_id<th>lname<th>fname<th>ssn<th>sex<th>course_id<th>desc<th>price');                   
    }

    if (document.getElementById("JSON").checked)                    //if JSON is requested
    {
        returnedArrObj = JSON.parse(text);                          //convert JSON into JS array of objects

        lines = "<table> \n"

        header = returnedArrObj[0];                                 //get first array element as an object
        lines += "<tr>"
        for (var key in header)                                     //loop through each element of the object                    
            lines += "<th>"+ key +"</th>"                               //get the property names (col headers) 
        lines += "<tr> \n"            

        for (i=0; i < returnedArrObj.length; i++)                   //loop through all lines of the array
        {
            object = returnedArrObj[i];                             //each element in the array is an object
            lines += "<tr>"
            for (var key in object)                                 //loop through each element of the object                    
                lines += "<td>"+ object[key] +"</td>"               //get the property values (col values) 
            lines += "<tr> \n"            
        }
        lines += "</table> \n"
   }
    
    outputDiv = document.getElementById("output");                  //get reference to the div tag
    outputDiv.innerHTML = lines;                                    //output the response 
    outputDiv.style.visibility = "visible";                         //make the output area visible
}

//====================================================================================================
// alertError: alert and display an error (if no good) 
//====================================================================================================
function alertError(error)
{
    alert(error);
    outputDiv = document.getElementById("output");                  //get reference to the div tag
    outputDiv.innerHTML = error;                                    //output the response 
    outputDiv.style.visibility = "visible";                         //make the output area visible
}

</script>
</body>
</html>