HTML and CSS Reference
In-Depth Information
The POST Method.
In Example 18.17, rather than repeating the previous example in
its entirety, only the code where changes are made for the POST method is highlighted.
The
setRequestHeader
for the
Content-type
has been added and the
send()
method con-
tains the query string data that will be sent to the server. The line controlling caching
has been removed, because with the POST method caching is not an issue. The output
is identical to what is shown in Figures 18.16, 18.17, and 18.18.
EXAMPLE
18.17
/* Section of the Ajax Program highlighting changes to make a POST
request */
ajaxRequest.onreadystatechange = function(){
var textObj;
textObj=document.getElementById("message");
if(ajaxRequest.readyState == 4){
if(ajaxRequest.status==200){
textObj.innerHTML=ajaxRequest.responseText;
}
}
else if(ajaxRequest.status == 404){
textObj.innerHTML="Resource unavailable";
}
else{
textObj.innerHTML="Error!! Firefox request aborted.
Status: "+ajaxRequest.status;
}
}
var namevalue=
encodeURIComponent(document.getElementById("username").value)
var phonevalue=
encodeURIComponent(document.getElementById("userphone").value)
/* This is where the code changes for the POST method */
1
ajaxRequest.open("POST", "http://localhost/ajaxform.php")
2
ajaxRequest.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
3
ajaxRequest.send("username="+namevalue+
"&userphone="+phonevalue);
}
</script>
</head>
<body>
4
<form>
Your name: <input type="text" size=50 id=username
name='username' /> <br />
<p>
Your phone: <input type="text" size=50 id=userphone
name="userphone" /><br />
Continues