Earthquake
Hmm, an earthquake ... 10:49 NZDT felt in Dunedin, went on for about a minute. Slight rolling/shaking, kind of cool :)
<select id="genre" />That's all that we need for this as we're going to populate it with options after the server responds to our request. We'll add a button to click as well that runs our function:
<input type="button" onClick="populate();" value="Ajax GO!" />And finally, the populate function goes in our Javascript:
function populate()The above function makes an Ajax request to the url
{
new Ajax.Request('genres.php',
{
onSuccess: function(trans)
{
var response = trans.responseText.evalJSON();
for (var i=0; i<response.genres.length; i++)
$('genre').options[i] = new Option(response.genres[i],response.genres[i]);
},
onFailure: function(trans) { alert('An error occurred: '+trans.statusText); }
});
}
genres.php and on getting the response it runs the onSuccess function. This function decodes the JSON response and then loops through each item adding it to the select box.<?phpIn addition to the above you must actually load the prototype.js library. Take a look at the source of the above in action to see how it hangs together.
echo json_encode(array('genres'=>array(
'Blues',
'Country',
'Funk',
'Jazz',
'Pop',
'Rock'
)));
?>