Writing Simple Ajax Example
We have to write the required JavaScript code to make the server call ( to call sayhello.php) by passing the user name. Here is the complete code of the simpleajaxexampledemo.html file:
<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function postRequest(strURL) {
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}else if (window.ActiveXObject) { // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
updatepage(xmlHttp.responseText);
}
}
//Note: When you use async=false, do NOT write an onreadystatechange function - just put the //code after the send() statement://xmlhttp.open("GET","ajax_info.txt",false);xmlHttp.send(strURL); } function updatepage(str){ document.getElementById("result").innerHTML = "<font color='red' size='5'>" + str + "</font>";; } function SayHello(){ var usr=window.document.f1.username.value; var rnd = Math.random(); var url="sayhello.php?id="+rnd +"&usr="+usr; postRequest(url); } </script> </head> <body> <h1 align="center"><font color="#000080">Simple Ajax Example</font></h1> <p align="center"><font color="#000080">Enter your name and then press "Say Hello Button"</font></p> <form name="f1"> <p align="center"><font color="#000080"> Enter your name: <input type="text" name="username" id="username"> <input value="Say Hello" type="button" onclick='JavaScript:SayHello()' name="showdate"></font></p> <div id="result" align="center"></div> </form> <div id=result></div> </body> </html>
//xmlhttp.send();
//document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
We are using the xmlHttp object to send the query to the server using the function xmlHttp.send(strURL).
When the response from the server is ok, calling the updatepage() function.
if (xmlHttp.readyState == 4) {
updatepage(xmlHttp.responseText);
}
updatepage(xmlHttp.responseText);
}
Finally the in the updatepage function we are adding the response text into the <div> </div> for displaying it to the user.
function updatepage(str){
document.getElementById("result").innerHTML =
"<font color='red' size='5'>" + str + "</font>";;
}
document.getElementById("result").innerHTML =
"<font color='red' size='5'>" + str + "</font>";;
}
In the php file we are retrieving the data from user and then sending the appropriate message to the user. Here is the code of sayhello.php.
No comments:
Post a Comment