2

I have the following example.


userview.php

<script>
        $(document).on("ready", function(){
            loadData();
        }); 

        var loadData = function(){
            $.ajax({
                type:"POST",
                url:"Users.php"
            }).done(function(data){
                console.log(data);
                var users = JSON.parse(data);
                for(var i in users){
                    $("#content").append(users[ i ].usuario + " " + users[ i ].nombres + "<br>");
                }
            });
        }

    </script>

users.php

  <?php
    $bd = "test";
    $server ="localhost";
    $user = "root";
    $password = "";

    $conexion = @mysqli_connect($server, $user, $password, $bd);

    if( ! $conexion )   die( "Error de conexion ".mysqli_connect_error() );

    $sql = "SELECT usuario, nombres FROM usuario";
    $result = mysqli_query($conexion, $sql);
    $array_user = array();
    while($data = mysqli_fetch_assoc($result)){
        $array_user[] = $data;
    }

    echo json_encode($array_user);
?>

How can i reload the users (In case of update or delete) in userview.php without refreshing the page

5
  • 1
    make the loadData(); run, lets say, every 5 seconds. Commented Feb 6, 2016 at 19:06
  • i tried but i does not replace it. appears duplicated Commented Feb 6, 2016 at 19:10
  • 1
    Just empty the content of #content with $("#content").empty(); before appending again. I've added that to my answer. Commented Feb 6, 2016 at 19:19
  • now it works! thank you very much! Commented Feb 6, 2016 at 19:22
  • You're welcome, glad it worked out. Commented Feb 6, 2016 at 19:23

1 Answer 1

1

A solution would be making loadData() run, lets say, every 5 seconds, i.e.:

<script>
$(document).ready(function() {
    startLoop();
});

var frequency = 5000; // 5 seconds in miliseconds
var interval = 0;
// STARTS and Resets the loop
function startLoop() {
    if (interval > 0) clearInterval(interval); // stop
    interval = setInterval("loadData()", frequency); // run
}

function loadData() {
    $.ajax({
        type: "POST",
        url: "Users.php"
    }).done(function(data) {
        console.log(data);
        var users = JSON.parse(data);
        $("#content").empty();
        for (var i in users) {
            $("#content").append(users[i].usuario + " " + users[i].nombres + "<br>");
        }
    });
}
</script>
Sign up to request clarification or add additional context in comments.

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.