Reputation: 11763
I would appreciate any help on this issue.
Lets say I want to load controls for different items on the page AFTER it has finished loading.
So:
Object 1
<div id="controls1" class="controls" item_id="1"></div>
Object 2
<div id="controls2" class="controls" item_id="2"></div>
Object 3
<div id="controls3" class="controls" item_id="3"></div>
How could I use jQuery to popular the DIVs with class of "controls" using an AJAX call? In this case, I guess it will have to do 3 ajax calls to popular each DIV.
My ajax to grab content is ajax.php?request=controls&item_id=
Thanks!
Upvotes: 2
Views: 16878
Reputation: 4278
A basic way to do this is as follows:
$(document).ready(function() {
$('#controls1').load('ajax.php?request=controls&item_id=1');
$('#controls2').load('ajax.php?request=controls&item_id=2');
$('#controls3').load('ajax.php?request=controls&item_id=3');
});
A nicer way would be to dynamically determine how many 'controls' divs you have, and load them as needed... For example:
$(document).ready(function() {
$('.controls').each(function() {
var theId = $(this).attr('item_id');
$(this).load('ajax.php?request=controls&item_id=' + theId);
});
});
Good luck!
Update:
To avoid using the custom item_id
attribute, you could extract the ID you want from the element's ID, using a regular expression perhaps, like so... (warning, not tested)
$(document).ready(function() {
$('.controls').each(function() {
var theId = $(this).attr('id');
theId = /controls(\d+)/.exec(theId)[1];
$(this).load('ajax.php?request=controls&item_id=' + theId);
});
});
Upvotes: 6
Reputation: 342635
In addition to making repeated calls to $.load (or whatever) if you want to do that in a single ajax call, here are two options:
1 - Wrap all of those divs in another one, and have the server provide the entire content in a single request:
$(document).ready(function() {
$('#superDiv').load('foo.html');
});
2 - Send a json object to the client containing a ID/Content map
$(document).ready(function() {
$.get('foo.php', function(json) {
$('#controls1').html(json.controls1);
$('#controls2').html(json.controls2);
$('#controls3').html(json.controls3);
},"json");
});
Upvotes: 1
Reputation: 9098
This will find all the matching class="controls" divs, extract the item_id, and trip up to the server to grab the HTML.
More on the ajax load here: http://docs.jquery.com/Ajax/load#urldatacallback
$(document).ready(function() {
$('.controls').each(function(i) {
var itemId = $(this).attr('item_id');
$(this).load('ajax.php?request=controls&item_id=' + itemId)
});
});
Upvotes: 0
Reputation: 26583
Use jQuery.load().
This will populate the DOM of the target div (any element, as a matter of fact). But if you want to attach special functions to them, you need to do that explicitly after the load is completed (in the callback).
Simple event handlers can bet set to bind themselves automatically to new fetched content using jQuery.live() (as opposed to usig jQuery.bind())
Cheers!
Upvotes: 0