<!DOCTYPE html>
<html>
<head>
<title>Fetch call</title>
<meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
<style>
    #output {height:200px;width:350px; border:2px solid #cccccc; visibility:hidden; overflow:scroll}
    a       {color:black; text-decoration:none; display:block;}
    a:hover {color:white; background-color:#2554C7;}
</style> 
</head>

<body>
  <h2>Using Fetch - Search for city/state/country</h2>
  
  <table>
    <tbody>
        <tr>
            <td>Search For:</td>
            <td><input type="text"     id="search" style='width:350px' onKeyUp="doRequest();"/>
            <td><input type="checkbox" id="showData"/> Show returned Data 
            <td><input type="radio"    id="XML"  name="type" checked="on" /> XML
            <td><input type="radio"    id="JSON" name="type"              /> JSON
         </tr>
         <tr>
             <td></td>
             <td><div id="output"></div>
         </tr>
    </tbody>  
  </table>
  
<script>

var url = "https://storm.cis.fordham.edu/~sultan/web/demo/php/searchDB.php"    //server process to call                                 

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

    param = "name=" + searchStr;                               //create the parameters to be sent

    if (document.getElementById("XML").checked)                 //if XML is requested
        param += "&format=XML";
    if (document.getElementById("JSON").checked)                //if JSON is requested
        param += "&format=JSON";

    url_param = url + "?" + param                               //url plus paramaters

    promise1 = fetch(url_param)                                 //fetch() method retrieves a url, and returns a Promise
        
    promise1.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 standard 
//         - JSON string in format: [ {'name':'value', 'name':'value', ...}, {'name':'value', ...} ]
//====================================================================================================
function doResponse(responseObj)
{
//  alert(promiseObj.status +"-"+ promiseObj.statusText)        //for debugging: Should print 200-OK (or 404-NOT FOUND, or ...)

//  for (prop in promiseObj)                                    //for debugging: dump the entire promise object
//      alert(prop + '->' + promiseObj[prop])

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

    lines = "";

    if (document.getElementById("XML").checked)                     //if XML is requested
    {                                                               //and create an array
        returnedLines = content.split(/\n/);                        //split the returned lines on \n into an array

        for (i=1; i<returnedLines.length; i++)                  
            if (returnedLines[i].indexOf('<name>') >= 0)            //if this is the <name> element
            {
                lines += "<nobr><a href=searchResult.html?" + searchStr + ">"; 
                lines += returnedLines[i] + '-'; 
                lines += '<i>' + returnedLines[i+1] + '</i>'; 
                lines += "</a></nobr>";
            }     
    }

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

        for (i=0; i < returnedArrObj.length; i++)                   //loop through all lines as an array
        {
            object = returnedArrObj[i];                             //each line is an object                

            lines += "<nobr><a href=searchResult.html?" + object['name'] + ">" 
            lines += object['name'] + ' - ';                        //the name property 
            lines += '<i>' + object['type'] + '</i>';               //the type property
            lines += "</a></nobr>"; 
        }
    }
    
    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 the fetch error (if no good) 
//====================================================================================================
function alertError(error)
{
    alert(error);
}

</script>

</body>
</html>