0

i have multiple divs with same class and different id and i want to change div contents auto every 10 seconds. need to post div id to my php page and update result to div...

<div class="sayac" id="1">data1</div>
<div class="sayac" id="2">data2</div>
<div class="sayac" id="3">data3</div>
<div class="sayac" id="4">data4</div>
Edursun
  • 21
  • 5

2 Answers2

0

Here you just need to use setInterval() with ajax function to refresh your div, Please try

$(document).ready(function () {
  var mayVar = setInterval(refreshDiv,10000);
  
});
function refreshDiv(){
//you can call here ajax to refresh every 10 seconds
    $('#1').html(Math.random().toString(36).substr(2, 5));
    $('#2').html(Math.random().toString(36).substr(2, 5));
    $('#3').html(Math.random().toString(36).substr(2, 5));
    $('#4').html(Math.random().toString(36).substr(2, 5));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sayac" id="1">data1</div>
<div class="sayac" id="2">data2</div>
<div class="sayac" id="3">data3</div>
<div class="sayac" id="4">data4</div>
M.Hemant
  • 2,345
  • 1
  • 9
  • 14
  • But i need to post id and need to get data from this id then i can update div with this new data... – Edursun Jun 15 '19 at 20:16
  • Do you mean from div `id` you need to get data? if yes then fetch all `id` from `class` attribute and send it to ajax – M.Hemant Jun 17 '19 at 03:42
  • yes i mean i need to get data from div id, yes but i dont now how to do...i thin i need to learn javascript – Edursun Jun 17 '19 at 05:57
0

A quick way would be:

setInterval(function(){
    $('.sayac').each(function(index, el) {
        var thisID = $(this).attr('id');
          $.post( "path/to/file.php", { 
            id: thisID
          })
          .done(function(data, status) {
            $('#'+thisID).html(data); //$(this) will not work here
          })
          .fail(function(data, status) {
            console.log( "error" );
          });
    });
},10000);

But there is not much error handling. I would also suggest that your php to ouptuts in json. This way you can return an array and have your code react accordingly.

hexYeah
  • 1,040
  • 2
  • 14
  • 24