It’s time to build a few JavaScript applications to see what jQuery can do for you when you’re retrieving results from AJAX calls. Although your real-world situations will be more complex, the process is going to be the same.
How to work with standard output
This example uses the DoMath.php script to perform math and change just the result field of a form on a page. You must use your server setup to make this example work because the server executes the PHP script and then returns the result. Using jQuery makes the process of working with AJAX significantly easier. The following code shows the form used for this task.
<form id="DataEntry"> <h1>Scripting an Addition Routine with AJAX</h1> <div> <label>Value 1:</label> <input id="val1" name="val1" value="1" type="text" /> </div> <div> <label>Value 2:</label> <input id="val2" name="val2" value="2" type="text" /> </div> <div> <label>Result:</label> <span id="result"></span> </div> <input id="btnChange" type="button" value="Add the Numbers" onclick="PerformAdd()" /> </form>
The example uses standard controls for data input. Notice that you must define the name attributes for these controls, or the jQuery .serialize() method won’t work. It’s a good idea to assign the controls default values. The output is a simple .
The application performs its task when the user clicks Add the Numbers, which is an control. This approach provides an alternative to using a submit style button. However, either approach works equally well. The advantage of this approach is that you can use a named function, PerformAdd(), to handle the click event. The following code shows how PerformAdd() does its work:
function PerformAdd() { $("#result").load( "http://localhost/DoMath.php", $("#DataEntry").serialize()); }
The example places the output in a with an id of result. You access this by its identifier and call load() to fill it with information from the desired source. You provide the location of the source, which is DoMath.php.
The PHP script requires input data, which you add as a second argument. To obtain the data, you access the