HTML and CSS Reference
EXAMPLE 18.13 ( CONTINUED )
9 <input type="button" value="submit" onClick="goAjax() "; />
10 <div id="message" class="divStyle">
The goAjax() function is returned an XMLHttpRequest object from the createRe-
quest() function found in the external .js file called “ajaxCreateRequest.js” shown
in Example 18.14. The CSS style sheet is in Example 18.15.
The onreadystate event handler will start the callback function when the state of
the server request changes.
The getElementById() method will return a reference to the div container using its
id called “message”.
When the server has completed successfully, its response will be returned as text.
The innerHTML property contains the response text that is assigned to the div
container on line 10 and will be displayed in the browser.
To avoid unexpected requests to the server, the encodeURIComponent encodes any
user-entered parameters that will be passed as part of a URI . The value typed by
the user into the form for the username will be assigned to the variable namevalue .
The XMLHttpRequest object is initialized. It will use the GET method. The URL is
a server-side PHP program (Example 18.16) that will be passed parameters, ap-
pended to a ?, consisting of the user's name and phone number.
An XMLHttpRequest is sent to the server.
The HTML form starts here. Notice the ACTION and METHOD attributes are
NOT specified as they are in non-Ajax forms.
Even though this button looks like a “submit” button, it is really an ordinary but-
ton with an onClick event handler that when clicked, will start the goAjax() func-
tion. In non-Ajax form submission, the submit button normally causes the con-
tents of the form to be sent to the URL assigned to the form's ACTION attribute.
The div container will display the results that were returned to the server from
the PHP program listed as a parameter in the open() method on line 6.