|
<form method="post" action=""> <button value="all" type="submit">Get All Wines!</button> <button value="red" type="submit">Get Red Wines!</button> <button value="white" type="submit">Get White Wines!</button> </form> <div id="wines"> <!-- Javascript will print data in here when we have finished the page --> </div> |
<script type="text/javascript"> $(document).ready(function(){ $(':submit').on('click', function() { // This event fires when a button is clicked var button = $(this).val(); $.ajax({ // ajax call starts url: 'serverside.php', // JQuery loads serverside.php data: 'button=' + $(this).val(), // Send value of the clicked button dataType: 'json', // Choosing a JSON datatype success: function(data) // Variable data contains the data we get from serverside { $('#wines').html(''); // Clear #wines div if (button == 'all') { // If clicked buttons value is all, we post every wine for (var i in data.red) { $('#wines').append('Red wine: ' + data.red[i] + '<br/>'); } for (var i in data.white) { $('#wines').append('White wine: ' + data.white[i] + '<br/>'); } } else if (button == 'red') { // If clicked buttons value is red, we post only red wines for (var i in data) { $('#wines').append('Red wine: ' + data[i] + '<br/>'); } } else if (button == 'white') { // If clicked buttons value is white, we post only white wines for (var i in data) { $('#wines').append('White wine: ' + data[i] + '<br/>'); } } } }); return false; // keeps the page from not refreshing }); }); </script> |
<?php // Get value of clicked button $button = $_GET['button']; // Red wine table $red = array('Chianti', 'Barolo', 'Pinot Noir'); $white = array('Chardonnay', 'Cava', 'Chablis'); // Combine red and white tables into one multidimensional table $winetable = array( "red" => $red, "white" => $white, ); // Finally depending on the button value, JSON encode our winetable and print it if ($button == "red") { print json_encode($red); } else if ($button == "white") { print json_encode($white); } else { print json_encode($winetable); } ?> |