Using jQuery, how can I populate the value of table cells using an AJAX call, when the table cell itself is being programatically generated?
I am building a page that works as follows:
- Perform initial AJAX call, expecting a JSON array, e.g. a list of item names
- AJAX callback uses
jQuery.each
to iterate through the array - The callback for each array item adds a row to the table, with the item name
- There are additional cells (let's say they represent item locations) but to get the value of this, another AJAX call needs to be made (marked as
*
in the sample) - how might I implement this functionality?
Sample table structure:
Name Location1 Location2
================================
Item1 * *
Item2 * *
Other considerations:
- Need to cater for a dynamic number of columns, i.e. locations. This is why I
- I know there are a large number of calls, but not concerned about that for this question
- I am using the DataTables plugin
- I would like to understand whether this can indeed be done without simply changing the web services backend to generate the whole table, or at least a row at a time. By performing a query per-cell I can re-use existing calls.
Note: I am adding the table rows by using the following code, which I am open to altering. Reference
$("#tableID").find("tbody").append($('<tr>')
.append($('<td>').text(...))
.append($('<td>').text(...))
.append($('<td>').text(...))
);
I'm thinking I could probably generate IDs for each cell and then fire off the AJAX calls based on that, but that seems a little clunky. Is there any more elegant way to do this?
Ideally any solution would also be able to be adjusted to handle the use case of adding an extra column to the table, e.g. Location3 in the sample table above.