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:
<script type="text/javascript">
$("#IDofInput").change(function(){
$var = $("#IDofInput").attr(value);
$.post("path to server-side file",{var:$var}, function(data) {
$("#IDofElementToUpdate").html(data);
});
});
</script>
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.






[...] Finally, back in the main page, we’ll use jQuery to asynchronously trigger the “select_state.php” script, based on the technique outlined here. [...]
[...] posts it asynchronously to a PHP script named “determine_next_questions.php” (see the full explanation of this technique), which we’ll pretend generates questions based on the category chosen. The [...]