A while back I wrote a series dealing with loading content and JSON data with jQuery and AJAX which culminated in the post "Load JSON data with jQuery, PHP and MySQL" which brought all the techniques together and loaded JSON data into select boxes when the first was changed. I was recently asked how to do this using radio buttons instead, which I show how to do in this post.
Previous posts
The previous posts mentioned above covered loading JSON data with jQuery, converting an array to JSON with PHP, and fetching data from a MySQL database with PHP PDO using data from my example fruit table. A couple of other relevent posts are how to iterate through an associative array, get and set form element values and adding a new option to a select with jQuery.
Working example
The example below doesn't actually make a JSON call with jQuery but does illustrate how the example detailed in this post works.
HTML Code
The initial HTML code looks like this:
The set of fruit names was already populated on the server-side and the default set of varieties could be too; I have chosen to populate them with Javascript in this example.
jQuery Code
The jQuery code needs to initially populate the variety span with radio buttons based on the value of the selected fruit radio button. It then needs to update the variety if the fruit selection changes.
Assuming the PHP script to fetch the fruit is at /fruit-varieties.php do this:
The $.getJSON line retrieves the data via an AJAX request, passing it the currently selected fruit name. The data is then looped through (it's an array containing the index 'variety' containing the fruit variety name) and added to an html string, which is then finally injected into the web page's #varieties span replacing what was previously there.
Caching issues
Internet Explorer and Firefox will cache the subsequent requests made to the same fruit name but the other browsers might not, requesting them again each time. There are a couple of ways to solve this which is covered in another post.
0 comments:
Post a Comment