CoderYordi CoderYordi - 14 days ago 5
Ajax Question

Refreshing data output from database (PHP)

So, I have this code below which gets the data from my database, but I want this data to 'Refresh' Every 5 seconds so that when something new is put in the database which is matching the specifications shows up. (I don't want the page to refresh for this, only data...)

$sql = "SELECT * FROM items WHERE reference = '1' ORDER BY datePosted asc LIMIT 5";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$title = $row["titel"];
$description = $row["description"];
}
} else {
echo "Nothing found";
}


I've been looking for AJAX and PHP ways to do this, but I just don't seem to figure it out... Any help / info is appreciated!

Answer

You could use something like this;

<div id='contentToUpdate'></div>


<script type="text/javascript">


    setInterval(function(){
        LoadContent(); // this will run after every 5 seconds
    }, 5000);


    function LoadContent(){

        $.ajax({

            type:"POST",
            url: "/path/to/script.php",
            data: {GenerateContent: true, PostName2: 'value2'},

            success: function(result){

                $("#contentToUpdate").html(result);

            }, error: function(result){

                alert('something went wrong');

            }, complete: function(result){

                // fires regardless of above

            }

        });

    }

</script>

In the php file the receives the Ajax request you could have something like this;

    if(isset($_POST['GenerateContent'])){


        $aResults = array();

        $sql = "SELECT title, description FROM items WHERE reference = '1' ORDER BY datePosted asc LIMIT 5";
        $result = $conn->query($sql);

        while($row = $result->fetch()){
            $aResults[] = array('title' =>$row['title'], 'description' => $row['description']);
        }


        // if there are results output them
        if(!empty($aResults)){

            // foreach result
            foreach ($aResults as $iKey => $aResult) {
                echo "<p>";
                echo "Title: ".$aResult['title']."<br>\n";
                echo "Description: ".$aResult['description']."<br>\n";
                echo "</p>";
            }

        }else{
            echo 'No results have been loaded';
        }


        exit;
    }
Comments