Ajax: Ajax.html

<html>
<head>

<title>Comp 86 example Ajax</title>
<!-- Using asynchronous server call with ascyn/await, reply comes in text -->

<script>

class Main {
    constructor () {
	inputText.addEventListener ("keyup", this.getReply) //*1 Install callback, get text from event target
    }

    // Called on key up
    async getReply (event) { //*6 If you use await, function must be async 
	let inp = event.target.value //*1
	let response = await fetch ("Ajax.php?input=" + escape(inp)) //*2 Send request to server and WAIT
	if (response.ok) { //*3 Check for error
	    let ans = await response.text() //*4 WAIT for text response

	    // Separate out the 4 lines 
	    let lines = ans.split("\n"); //*5 Plug returned values into HTML
	    outputText.textContent = lines[0]; //*5
	    server.textContent = lines[1]; //*5 
	    software.textContent = lines[2]; //*5 
	    time.textContent = lines[3]; //*5 
	}
    }
}

window.onload = function () { new Main() }

</script> 
</head>

<body>

<i>Your input: </i>
<input type="text" id="inputText" />

<p>
<i>Output: </i><span id="outputText"></span>
</p>

<hr>

<p>
Server is
<b><span id="server"></span></b>
</p>

<p>
It is running 
<b><span id="software"></span></b>
</p>

<p>
Time on the server is
<b><span id="time"></span></b>
</p>

</body>
</html>
[download file]