Reputation: 3839
I'm trying to asynchronously load data from mysql. First, on page load I add multiple divs to the page:
$(document).ready(function(){
// Layout
var main = $("#main-div");
for(var i = 0; i < array.length; ++i) {
main.append("<div class='container'><a href=\"blah\">"+array[i]+"</a><div class='button-container'><span id='playcount_"+array[i]+"' class='playcount' style='margin-right:5%'>nope</span></div></div>");
}
// Get info for each sound in array
for(var i = 0; i < array.length; ++i) {
$.post("script/php_getinfo.php", { "file": array[i] }, updatePlaycount, "json");
}
});
The container
divs are added with a span
with an id of playcount_A
, playcount_B
, etc. After the divs are added, a POST
is made per item in the array and calls updatePlaycount
upon success.
updatePlaycount attempts to select the element and insert text into the span
:
function updatePlaycount(data) {
$('#playcount_'+data.name).text(data.playcount);
}
The function correctly gets the data.name
and data.playcount
fields (for example A
and 1
), but for some reason jQuery cannot find #playcount_A
! Surely they've been added already, since there's no loading involved with adding the divs...
Upvotes: 0
Views: 85
Reputation: 1598
It works for me. Doesn't seem like that much code to demo. fiddles can use ajax by the way so if you have a (big) library to include you can do that too
$(document).ready(function () {
// Layout
var main = $("#main-div"),
array = ["A", "B", "C"],
updatePlaycount = function (data) {
console.log(data);
var $playct = $('#playcount_' + data.name);
console.log($playct);
$playct.text(data.playcount);
}
function ajaxI(i,arr){
var J= JSON.stringify({
"name": arr[i],
"playcount": (i+1)+''
});
console.log(J)
$.ajax({
type : "POST",
dataType: "json",
url: "/echo/json/",
data: {
json: J,
delay: 3
},
success: updatePlaycount
});
}
for (var i = 0; i < array.length; ++i) {
main.append("<div class='container'><a href=\"blah\">" + array[i] + "</a><div class='button-container'><span id='playcount_" + array[i] + "' class='playcount' style='margin-right:5%'>nope</span></div></div>");
} // end for
// Get info for each sound in array
for (var j = 0; j < array.length; ++j) {
ajaxI(j,array);
} // end for
}); // end ready
please send cheque payable to... j/k
Upvotes: 2