Step 3–a Simple Example
<label>your Name: <input type= "text" id= "Ajaxtextbox"/></label><span id= "AjaxButton" style = "Cursor:pointer; Text-decoration:underline "> Make a request</span>
Get the user ' s data from the text box and send it to the makeRequest() function along with the URL of our server-side script:
document.getElementById ("Ajaxbutton"). onclick = function () { var userName = document.getElementById ("Ajaxtextbox "). Value; MakeRequest (' test.php ', userName); };
We need to modify to makeRequest() accept the user data and pass it along to the server. We'll change the "request method from GET POST " to "and" include our data as a parameter in the httpRequest.send() "call to:
function makerequest (URL, userName) { ... Httprequest.onreadystatechange = alertcontents; Httprequest.open (' POST ', url); Httprequest.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded '); Httprequest.send (' username= ' + encodeuricomponent (userName)); }
The function alertContents() can be written the same-it is in Step 3 to alert we computed string, if that's all the server ret Urns. However, let's say the server is going to return both the computed string and the original user data. So if we have user typed "Jane" in the text box, the server's response would look like this:
{"userData":"Jane","computedString":"Hi, Jane!"}
To use this data within alertContents() , we can ' t just alert the responseText , we have to parse it and alert computedString , the property we want:
function alertcontents () { if (httprequest.readystate = = = Xmlhttprequest.done) { if (httprequest.status = = = 200 ) { var response = Json.parse (httprequest.responsetext); alert (response.computedstring); } else { alert (' There is a problem with the request ');} }
Ajax Basics (iii)