Location: Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
Posts: 7,686
Thanks: 42
Thanked 637 Times in 625 Posts
Happy world of JSON, also, using getJSON() function
I am noob to jQuery and JSON. Just found out about JSON actually. Wow lots of fun stuff there.
SO! I love jQuery's plugin library but I could not find a plugin that will "ajax" load a listbox using <optgroup> tags. I figure I can just use getJSON() to retrieve the data from my PHP script, right? So I code up a PHP script to return something that looks like:
And after that, use jQuery's JSON to parse the string.... something like:
Code:
$.post(
"yourphpfile.php",
{
action: "loadoptgroup"
},
function(data) {
data = JSON.parse(data);
// And here you loop through the array (data) and generate your objects via JS.
}
)
Not sure if this is what you were looking for, but it does do the trick... at least it does so for me... and well, it's easy to modify the array structure to include a label for each group.
__________________
The way to success is to assume that there are no impossible things. After all, if you think something is impossible, you will not even try to do it.
Location: Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
Posts: 7,686
Thanks: 42
Thanked 637 Times in 625 Posts
Yeah... looks good. I think the getJSON() function was getting me confused more than anything, but I've been googling for a while and I found this plugin and technique:
I'm a simple man so plugins are extremely appealing!
Using this plugin looks very similar to what you describe, so I'm going to forget about using getJSON() and go with a regular $.post, build PHP array and encode it (hopefully my PHP is upgraded to 5.2!) and that should work fine. Can't try it out until tonight... can't wait.
$.getJSON("options.php",{action:'loadoptgroup'}, function(json) {
var html = '<select>';
// Group 1
if (json.group1.type == 'optgroup')
{
html += '<optgroup label="'+json.group1.label+'">';
'</optgroup>';
}
for (option in json.group1.options)
{
html += '<option>'+json.group1.options[option]+'</option>'
}
if (json.group1.type == 'optgroup')
{
html += '</optgroup>';
}
// Group 2
if (json.group2.type == 'optgroup')
{
html += '<optgroup label="'+json.group2.label+'">';
'</optgroup>';
}
for (option in json.group2.options)
{
html += '<option>'+json.group2.options[option]+'</option>'
}
if (json.group2.type == 'optgroup')
{
html += '</optgroup>';
}
html += '</select>';
$('div#show_n_tell').html(html);
});
html:
Code:
<div id="show_and_tell"></div>
Last edited by GraphiteFingers; 06-21-2009 at 03:33 PM..
Reason: Added relevant example