Reputation: 4245
+----------------------+
| var1 | var2 | output |
+----------------------+
| .... | .... | .... |
+----------------------+
| .... | .... | .... |
+----------------------+
| .... | .... | .... |
+----------------------+
I have a table like which consists of two get variables var1
var2
.
echo'
<tr>
<td>'.$array[$num][0].'</td>
<td>'.$array[$num][1].'</td>
'.$script.' //bellow
<td><span class="output"></span></td>
</tr>
';
The rows are created dynamically from an array.
I am wanting the output column to be an ajax function that keeps refreshing.
Something like this:
$(function foo() {
$.get('foo.php', { var1: '".$var1."', var2: '".$var2."'}, function(data) {
if(data == '0'){
if (z > 100){
$('.output:first').html('timeout');
}else{
$('.output:first').html('not working');
setTimeout(function(){foo();}, 10000);
z++;
}
}else{
$('.output:first').html('working');
}
});
});
As seen above I am creating this script at the beginning of each row.
But I am having lots of issues where the classes and functions where they must be overwriting each other, is there a better way to do this? And if not how do I prevent all this overwriting.
I have looked into creating a new function for each row but that still leads to overwriting.
Also please bare in mind that there may be more than one of these tables on one page.
Upvotes: 0
Views: 478
Reputation: 781380
Put $var1
and $var2
in the HTML, and then use a jQuery loop to get all of them and make the AJAX calls for the corresponding row.
I also made the counter a parameter to the function, and increment it when recursing. Your code used a global variable z
for this, so each row was stepping on the counter of the other rows.
PHP:
echo'
<tr>
<td>'.$array[$num][0].'</td>
<td>'.$array[$num][1].'</td>
<td><span class="output" data-var1="'.$var1.'" data-var2="'.$var2.'"></span></td>
</tr>
';
JS:
$(function() {
function update_output(cell, count) {
$.ajax('foo.php', { var1: cell.data('var1'), var2: cell.data('var2') }, function(data) {
if (data == '0') {
if (count > 100) {
cell.html('timeout');
} else {
cell.html('not working');
setTimeout(function() {
update_output(cell, count+1);
}, 10000);
}
} else {
cell.html('working');
}
}
}
$('.output').each(function() {
update_output($(this), 0);
});
});
Upvotes: 1