i am trying to change inner HTML of a div after some interval. i am getting right response which i want with Ajax. but unable to replace inner HTML of selected after and with Ajax response. what is wrong with my code..
Html
<p class="time ui-li-desc" data-time="2013-02-13 11:30:08" >
51 seconds ago<img alt="image" src="images/read.png"></p>
<p class="time ui-li-desc" data-time="2013-02-13 11:30:16" >
58 seconds ago<img alt="image" src="images/read.png"></p>
.
.
.
.
.
<p class="time ui-li-desc" data-time="2013-02-13 11:40:08" >
10 minute ago<img alt="image" src="images/read.png"></p>
j query
setInterval(function() {
$( ".time" ).each(function( index ) {
var sendTime= $(this).attr("data-time");
dataString = "sendtime="+sendTime+"&q=convertTime";
$.ajax({
type: "POST",
url: "data_handler.php",
data: dataString,
cache: true,
success: function(response) {
alert(response);
$(this).html(response);
//alert(response);
}
});
});
}, 5000);
this
is the window in the callback. Use the value given to the callback
of each :
$( ".time" ).each(function(index , elem) {
var sendTime= $(this).attr("data-time");
dataString = "sendtime="+sendTime+"&q=convertTime";
$.ajax({
type: "POST",
url: "data_handler.php",
data: dataString,
cache: true,
success: function(response) {
alert(response);
$(elem).html(response);
}
});
});
You don't need to define a new variable to protect this
as jQuery already does it for you.
As you are using an asynchronous function with a callback, this
in your callback doesn't come from the same context. You need to save this
in a variable used in the callback.
Try like this:
setInterval(function() {
$( ".time" ).each(function( index ) {
var sendTime= $(this).attr("data-time");
dataString = "sendtime="+sendTime+"&q=convertTime";
var self = this;
$.ajax({
type: "POST",
url: "data_handler.php",
data: dataString,
cache: true,
success: function(response) {
alert(response);
$(self).html(response);
//alert(response);
}
});
});
}, 5000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With