Hi this is an example of the code i want to run:
$('#search1').submit(function(){
var date = $('#date').val();
var location = $('#location').val();
var datastring = 'date=' + date + '&location=' + location;
$.ajax({
type: "POST",
cache: "true",
url: "search.php",
dataType:"json",
data: datastring,
success: function(data){
$('#main').html('')
for ($i = 0, $j = data.bus.length; $i < $j; $i++) {
//Create an object for each successful query result that holds information such as departure time, location, seats open...
$('#main').append(html);
}
How would I go about coding the success function? I want the object to store each bus’ information so that the info can be displayed in the search result as well as being able to be referenced when the user confirms his RSVP later on. Thanks ahead of time
You can declare an object to use as a map in the containing scope:
…and then if the bus entries have some form of unique identifier, you can record them like this:
And then later, when the user chooses a bus, use the chosen ID to get the full bus information:
This works because all JavaScript objects are key/value maps. Keys are always strings, but the interpreter will happily make strings out of what you give it (e.g.,
busInfo[42] = ...will work,42will become"42"implicitly).If you just want an array, your
data.busalready is one, right?(Note that JavaScript arrays aren’t really arrays, they too are name/value maps.)
Update: I dashed off a quick example of the keyed object (live copy):
HTML:
JavaScript with jQuery:
Data:
Off-topic: Note that I’ve added
var $i, $j;to your success function. Without it, you’re falling prey to The Horror of Implicit Globals, which you can tell from the name is a Bad Thing(tm).