Reputation: 1914
Yesterday I ask a question about json
Link: How to return an array from jQuery ajax success function and use it in a loop?
And one of the answers was this
setInterval(updateTimestamps,30000);
var ids = new Array();
function updateTimestamps(){
$(".timestamp").each(function(i){
var obj = new Object();
obj.id = $(this).attr("postID");
obj.timestamp = $(this).attr("postdate");
ids.push(obj);
}
$.post("http://site.com/ajax/humanTime.php", {"time": ids}, function(data) {
for (i = 0; i < data.length; i++) {
$("#" + data[i].id).html(data[i].content);
}
}, "json");
}
The problem with this script is that the data is dublicated
The first time when this is executed is something like this
Array
(
[0] => Array
(
[id] => 26629
[timestamp] => 1332273712
)
[1] => Array
(
[id] => 26628
[timestamp] => 1332243526
)
[2] => Array
(
[id] => 26627
[timestamp] => 1332237777
)
And the second time is
Array
(
[0] => Array
(
[id] => 26629
[timestamp] => 1332273712
)
[1] => Array
(
[id] => 26628
[timestamp] => 1332243526
)
[2] => Array
(
[id] => 26627
[timestamp] => 1332237777
)
[3] => Array
(
[id] => 26629
[timestamp] => 1332273712
)
[4] => Array
(
[id] => 26628
[timestamp] => 1332243526
)
[5] => Array
(
[id] => 26627
[timestamp] => 1332237777
)
)
I try with var ids= Array(); , vas ids = []; but that dosent work
Upvotes: 1
Views: 120
Reputation: 272106
Set ids = []
before you start pushing new items. Here is your code, re-factored:
var ids;
function updateTimestamps() {
ids = []; // <-- the answer
$(".timestamp").each(function(i) {
ids.push({
id: $(this).attr("postID"),
timestamp: $(this).attr("postdate")
});
});
$.post("http://site.com/ajax/humanTime.php", {"time": ids}, function(data) {
for (var i = 0; i < data.length; i++) {
$("#" + data[i].id).html(data[i].content);
}
}, "json");
}
setInterval(updateTimestamps, 30000);
Upvotes: 3
Reputation: 122906
A short way to reset an array: ids.length = 0;
. So
function updateTimestamps(){
ids.length = 0;
// [...]
}
Upvotes: 3
Reputation: 160833
setInterval(updateTimestamps,30000);
function updateTimestamps(){
var ids = []; // put it here
$(".timestamp").each(function(i){
var obj = {};
obj.id = $(this).attr("postID");
obj.timestamp = $(this).attr("postdate");
ids.push(obj);
}
$.post("http://site.com/ajax/humanTime.php", {"time": ids}, function(data) {
for (i = 0; i < data.length; i++) {
$("#" + data[i].id).html(data[i].content);
}
}, "json");
}
Upvotes: 2
Reputation: 123377
try this:
var ids;
function updateTimestamps(){
ids = [];
...
Upvotes: 2