user11092493
user11092493

Reputation:

Refresh an element only on page load and call on a function in javascript , jquery , ajax

I just want to update the #task div only on page load and when I call it on another function (Like on click a button). But in my code it is constantly refreshing the div because of setInterval() function.

Here is my Code

// FETCH ALL TASKS
$(function() {
  $.ajax({
    url: '<?php echo base_url() ?>alltasks',
    data: 'get',
    success: function(data) {
    $("#tasks").append(data);
    }
  })
});       
        
// REFRESH THE TASK AREA EVERY 2S
$(setInterval(function() {
  $('#task').load("<?php echo base_url() ?>alltasks");
}, 2000))

        
        

Thanks in Advance

Upvotes: 0

Views: 202

Answers (1)

LIGHT
LIGHT

Reputation: 5712

HTML

<div id="tasks"></div>
<button onclick="readTasks()">Read Tasks</button>

Javascript

function readTasks(){
    $('#task').load("<?php echo base_url() ?>alltasks");
}

$(document).ready(function(){
    readTasks();
});

Make sure that you load Javascript at the footer.

Upvotes: 1

Related Questions