Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use load() to refresh a div without duplicating the element?

Tags:

jquery

I use this code to refresh a div with the id="my":

<script type="text/javascript">
function recp() {
  setInterval(function() 
{
    $("#my").load(location.href+ ' #my');
});
}
</script>


<div id="my"><?php echo date('a:i:s'); ?></div>

It works, but it generates this code:

<div id="my"><div id="my">pm:25:40</div></div>

How can refresh the div without generating a double div?

In other words how can refresh only this div:

<div id="my"><?php echo date('a:i:s'); ?></div> 
like image 872
Morteza Avatar asked Dec 14 '11 22:12

Morteza


2 Answers

add another div as a container and load content to it, like that.

<script type="text/javascript">
function recp() {
  setInterval(function() 
  {
    $("#result").load(location.href+ ' #my');
  });
}
</script>

<div id="result">
  <div id="my"><?php echo date('a:i:s'); ?></div>
</div>
like image 194
Kokers Avatar answered Dec 03 '22 07:12

Kokers


Alter your code to use $.get() instead of .load()

<script type="text/javascript">
function recp() {
  setInterval(function() {
      $.get(location.href, function(data){ 
          $('#my').empty().append( $(data).find('#my').children() );
      });
  });
}
</script>
like image 34
Gabriele Petrioli Avatar answered Dec 03 '22 05:12

Gabriele Petrioli