Asynchronous page updates — updating page content without reloading the page — makes for a smooth, pleasant customer experience. But frankly, Ajax code can be intimidating and unintuitive. Sometimes you’d just like to keep it simple, and just run a server-side script without figuring out the ajax parameters.
With jQuery, it turns out to be pretty easy to trigger a server-side action and import the results into your page.
The key here is the jQuery .post method, which allows you to send data to an external script, and then incorporate the results into your page.
Here’s the basic syntax:
This script shows a typical use case: Updating another element based on a selection or entry in a form element.
The script runs when the triggering element (“#IDofInput”, in this case) is changed in some way. Typically, #IDofInput would be a <select> list, in which case the change would be selecting an option from that list.
The first line of the function defines the variable you want to pass to the server-side script — in this case, the chosen value in the triggering element.
The second line declares the POST action. It specifies the server-side script to be used, the variables to be passed (in this case, “var” with the value of $var), and the postback function (a function to be executed after the server-side script runs).
The postback function just takes the output of the script (defined with the keyword “data”) and sticks it inside the element with ID “IDofElementToUpdate”.
Those last two steps of the post method (passing variables and the postback function) are optional.
If you pass variables, be sure to have code in your server-side script for reading those variables. A PHP script used with the above jQuery would have something like this:
<?php $variable = $_POST['var']; ?>
You could then use “$variable” in the PHP script.
For a walkthrough of a common application of this technique, see my post on country and state dropdowns.