Greetings for the absolute beginners out there, just dipping your toes in AJAX.
I'm curious to know what exactly triggers the continuous change in divMessage content when the text "myName" is altered.
1) It appears that the Javascript function process is always actively "listening", is this standard behavior for Javascript? Or are there specific events that prompt the repeated execution of "process"? 2) Does any function assigned to "body onload" run repeatedly? If so, how frequently does this repetition occur? 3) How can we ensure a single execution of the process function if needed?
4) I'm slightly puzzled because I assumed the body would load only once. However, could it be that after the "body onload" event, the "process" function gets called, which then modifies the "body" by updating divMessage, essentially triggering another "body onload" cycle again, followed by "process" and so on.. ?
Many thanks in advance for your assistance!
<head>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload='process()'>
Server requests your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
Contained within quickstart.js
function process()
{
// Proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// Retrieve the user-inputted name from the form
name = encodeURIComponent(
document.getElementById("myName").value);
// Call the quickstart.php page located on the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// Define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// Initiate the request to the server
xmlHttp.send(null);
}
}
// Callback function executed upon receiving a message from the server
function handleServerResponse()
{
// Continue only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// Status code 200 signifies successful completion of the transaction
if (xmlHttp.status == 200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
helloMessage = xmlDocumentElement.firstChild.data;
// Display the received data from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage+ '</i>';
}
}
}
}
In addition, here's the contents of quickstart.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$name = $_GET['name'];
// Generate output based on the user name received from the client
$userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don't know you!';
echo '</response>';
?>