Reputation: 270
I receive some data (JSON encoded) from a PHP script using $.getJSON. It consists of 10 datasets ({"key":"data",...}). I want to print all data by first fading out the old sting, then replacing it with the new one and finally fading it in. That shall happen within a loop.
When the dataset is processed, the function calls itself and gets the next 10 datasets to print them. And so on.
function getText(){
$.getJSON("getText.php",
function(data){
for(key in data){
//alert(key);
if($("#wrapper").css("display") == "block")
$("#wrapper").fadeOut(500);
$("#wrapper").html(data[key]).fadeIn(500);
}
});
//alert("end");
setTimeout(function(){
getText();
},20000);
}
With some alerts the right datasets are shown, but without them just the last or first data from the dataset is displayed.Can someone help me please?!
Simplified there's just one div (#wrapper). After the page has loaded and showed some info the function getText ist called the first time. Now the PHP script is called and we receive ten datasets. Each of those shall be displayed before the function calls itself again. For example: fade in wrapper, show data #1, fade out wrapper; fade in wrapper, show data #2, fade out wrapper, and so on till every data (out of ten) ist showed. The loop should somehow wait for the animations. And the text in the wrapper shall be replaced.
Upvotes: 0
Views: 586
Reputation: 5905
Given your update try this:
function getText(){
var storage = {};
$("#wrapper").html('').fadeOut(500);
$.getJSON("getText.php",
function(data){
storage.data = data;
});
for (var i in storage.data)
{
$("#wrapper").html(storage.data[i]).fadeIn(500).delay(5000).fadeOut(500);
if (i == storage.data.length-1)
{
setTimeout(function(){
getText();
},50000);
}
}
}
OR
setInterval('getText',20000);
function getText(){
var storage = {};
$.getJSON("getText.php",
function(data){
i = (typeof(storage.i) != "undefined") ? storage.i : 0;
setInterval(function() {
$("#wrapper").fadeOut(500).html(storage.data[i]).fadeIn(500);
storage.i = i+1;
},2000);
});
}
Upvotes: 1
Reputation: 910
So then, I think, this is +/- what you're looking for ..
function getText(){
$.getJSON("getText.php", function(data) {
var keys = [];
for(var key in data){
keys.push(key);
}
function displayData() {
var key = keys.pop();
$("#wrapper").html(data[key]).fadeIn(500, function(){
if(keys.length>0) {
// Still some data available ..
displayData();
} else {
// All data has been displayed .. get some new from server ..
getText();
}
});
}
// If some data is available, show first ..
if(keys.length>0) {
displayData();
}
});
}
Upvotes: 0