HTML and CSS Reference
In-Depth Information
EXAMPLE
18.13 (
CONTINUED
)
<p>
9 <input type="button"
value="submit" onClick="goAjax()
"; />
</form>
10 <div id="message" class="divStyle">
</div>
</body>
</html>
EXPLANATION
1
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.
2
The
onreadystate
event handler will start the callback function when the state of
the server request changes.
3
The
getElementById()
method will return a reference to the
div
container using its
id
called “message”.
4
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.
5
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
.
6
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.
7
An
XMLHttpRequest
is sent to the server.
8
The HTML form starts here. Notice the ACTION and METHOD attributes are
NOT specified as they are in non-Ajax forms.
9
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.
10
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.