1

I would like to display newly inserted data from database. I found the below code from another question and it does what I want but it only shows the data when clicked. So can someone tell me how can I make the data auto load every 5 secs?

 <script type="text/javascript">

 $(document).ready(function() {

  $("#display").click(function() {                

  $.ajax({    //create an ajax request to load_page.php
    type: "GET",
    url: "second.php",             
    dataType: "html",   //expect html to be returned                
    success: function(response){                    
        $("#responsecontainer").html(response); 
        //alert(response);
    }

});
 });
});

</script>

<input type="button" id="display" value="Display All Data" />
<div id="responsecontainer" align="center">

4 Answers 4

2
$(document).ready(function () {

    function load() {
        $.ajax({ //create an ajax request to load_page.php
            type: "GET",
            url: "second.php",
            dataType: "html", //expect html to be returned                
            success: function (response) {
                $("#responsecontainer").html(response);
                setTimeout(load, 5000)
            }
        });
    }

    load(); //if you don't want the click
    $("#display").click(load); //if you want to start the display on click
});
Sign up to request clarification or add additional context in comments.

1 Comment

Hi arun your code will hit for every 5 seconds. even if there is no action we are sending unnecessary request to server for every 5 sec.
0

Try to add setTimeout:

success: function(response){                    
    $("#responsecontainer").html(response);
    setTimeout(success, 5000);
}

Comments

0

You can use function setTimeout as a timer to trigger. For detail, please look at below code:

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

    var loadData = function() {
        $.ajax({    //create an ajax request to load_page.php
            type: "GET",
            url: "second.php",             
            dataType: "html",   //expect html to be returned                
            success: function(response){                    
                $("#responsecontainer").html(response);
                setTimeout(loadData, 5000); 
            }

        });
    };

Comments

0

You may use jquery's setInterval() or setTimeout() inside onload(); refer to the following questions, its answer explains well what you need exactly.

Calling a function every 60 seconds

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.