I'm having trouble running a jQuery .post
over each element in my table. The following is my code
HTML
<table>
<tr>
<td class="load_img"></td>
<td class="load_img"></td>
<td class="load_img"></td>
<td class="load_img"></td>
<td class="load_img"></td>
<td class="load_img"></td>
<td class="load_img"></td>
<td class="load_img"></td>
</tr>
</table>
javascript
$(document).ready(function(){
$("td.load_ads").html("<img src='/classified_ads4free/images/icons/ajax-loader.gif'>");
$("td.load_ads").each(function(){
var loading=$(this);
$.post('/classified_ads4free/self_coded_helpers/jpost_get_ads.php',function(data)
{
loading.html(data);
});
});
});
.POST PHP script
<?php
$index=rand(0,10);
echo $index;
?>
So what I'm trying to do here is to have each <td>
in my table load a random number but my problem now is that all the <td>
's loaded the same random number. Instead of each one having a random number from 0-10.
(this is just for illustration, I know its possible to generate a random number using jquery but the purpose why I need to do a .post
is because I will be running queries to get load images within these table elements.)
Thanks all for the help. Got it solved. What i did was to create an artificial variable index. Then have the index increment everytime i launch the .post with a new loop. Don't know why but it kind of work in the way i would like it to operate. My new javascript code as follows incase anybody needs it.
$(document).ready(function(){
$("td.load_ads").each(function(){
var loading=$(this);
var index=0;
$(this).html("<img src='/classified_ads4free/images/icons/ajax-loader.gif'>");
$.post('/classified_ads4free/self_coded_helpers/jpost_get_ads.php',{index:index},function(data){
loading.html(data);
index=index+1;
});
});
});
It is probably a problem of cache.
As your request is always the same, the browser send only one time the request.
Solutions are:
1/ add a html headerin your php script to not cache the answer:
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
2/ add a random parameter in the request
It seem's to be a caching problem.
The simplest workaround is, to add a random number to the url.
var d = new Date();
$.post( '/classified_ads4free/self_coded_helpers/jpost_get_ads.php'
+ '?_=' + d.getTime()
+ '&_=' + Math.random(),
function( data ) { /* stuff */ }
);
Have you tried this way:
$(document).ready(function(){
$("td.load_ads").html("<img src='/classified_ads4free/images/icons/ajax-loader.gif'>");
$.post('/classified_ads4free/self_coded_helpers/jpost_get_ads.php',function(data){
$.each($("td.load_ads"), function(){
var loading=$(this);
loading.html(data);
});
});
});
I think you should iterate in the success function.