Reputation: 13
I'm trying to append HTMl content into a div after gathering data through a PHP script that returns a JSON array. I successfully parsed the data returned into a string var with all the content i need, but it wont work on the first time. Checked vars with firebug and all loading and parsing ok. Can anyone help? Heres a sample of the full code: The first function loads the data from php script...
function LoadProds(idf){
if (idf){
request = '../controllers/returnprods.php?idfamilia='+idf;
$.getJSON(request,function(data){
if (!data.resultado){
nProds = data.length;
for (i = 0; i < nProds; i++){
htmlContent = '<div class="cartigo">\n <div class="cartigodetalhe">';
h1Content = ' <h1>'+data[i].nome+'</h1>'
h2Content = '<h2>'+data[i].preco+'€</h2> \n</div>'
imgContent = '<img src="images/products/'+data[i].fullpath+'" width="183px" height="87px"> \n </div>';
divproduto = htmlContent+h1Content+h2Content+imgContent;
sProdutos = sProdutos + divproduto;
}
ncurrPos = 0;
}
});
}else{
return "(empty)";
}
}
The second, uses the click() event to load the parsed data and changes the look
$(".cbotaogrande").click(function(){
activeid = "#"+$('img[src$=".png"]').attr("id");
if (activeid){
activeimg = $(activeid).attr("src");
activeimg = activeimg.substr(0,activeimg.length - 7)+".jpg";
$(activeid).attr("src", activeimg);
}
activebtn = $(this).attr("id");
activebtn ="#img"+activebtn.substr(4);
tmpsource = $(activebtn).attr("src");
$(activebtn).attr("src",tmpsource.substr(0,tmpsource.length-4)+"_on.png");
activebtn = "cgradiente"+activebtn.substr(4);
$(".cbotoestopo").attr("id",activebtn);
$(".clogo").attr("id",activebtn);
LoadProds($(this).attr("comment")); // Calls the load data function above...
$(".cartigo").remove(); // Remove divs existentes com produtos
if (sProdutos != ''){
$("#cprodutos").append(sProdutos);
sProdutos = '';
}else{
sProdutos = '';
}
});
Hope you can help me. Thanks in advance
Upvotes: 1
Views: 1961
Reputation: 15676
You need to include this section of code:
$(".cartigo").remove(); // Remove divs existentes com produtos
if (sProdutos != ''){
$("#cprodutos").append(sProdutos);
sProdutos = '';
}else{
sProdutos = '';
}
in your LoadProds()
function in the callback of $.getJSON()
.
$.getJSON()
makes an asynchronus call to fetch your data. What this means is that your javascript code won't stop and wait for this to finish before proceeding to the next line. So in your orignal code, after calling LoadProds()
it will proceed to the next if
block right away, before your data is fetched and the variables are set. This is why it appears to work the 2nd time, because when you try and click again, the data has been loaded by that point.
Upvotes: 1