Send Ajax request
1. obtain the required data from the web form.
2. Create the URL to be connected.
3. Open the connection to the server.
4. Set the function to run after the server completes.
5. Send a request.
Function callserver (){
// Obtain the city and state values from the form.
VaR city = Document. getelementbyid ("city"). value;
VaR state = Document. getelementbyid ("state"). value;
// Only go on if there are values for both fields
If (city = NULL) | (city = "") return;
If (State = NULL) | (State = "") return;
// Build the URL to connect
VaR url = "/scripts/getzipcode. php? City = "+ escape (city) +" & State = "+ escape (State );
// Open a connection to the server
XMLHTTP. Open ("get", URL, true );
// Setup a function for the server to run when it's done
XMLHTTP. onreadystatechange = updatepage;
// Send the request
XMLHTTP. Send (null );
}
1. The initial code uses the basic JavaScript code to obtain the values of several form fields.
Set a PHP script as the link target. Pay attention to the method specified by the Script URL. City and State (from the form) are appended after the URL with a simple get parameter.
2. Open a connection. This is the first time you see XMLHttpRequest.
3. The connection method (get) and the URL to be connected are specified. If the last parameter is set to true, an asynchronous connection is requested (this is the origin of Ajax ). If false is used, the code sends a request and waits for the response from the server. If this parameter is set to true, you can still use forms (or even call other Javascript methods) when the server processes requests in the background ).
4. The onreadystatechange attribute of XMLHTTP (Remember, this is an XMLHTTPRequest object instance) can tell the server what to do after it is completed (it may take five minutes or five hours. Because the Code does not wait for the server, you must let the server know how to do so that you can respond. In this example, if the server finishes processing the request, a special method named updatepage () will be triggered.
5. Finally, use null to call send (). Because the data (city and state) to be sent to the server has been added to the request URL, no data needs to be sent in the request. In this way, a request is sent, and the server works according to your requirements.