CoderYordi CoderYordi - 3 months ago 19
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!


You could use something like this;

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

<script type="text/javascript">

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

    function LoadContent(){


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

            success: function(result){


            }, error: function(result){

                alert('something went wrong');

            }, complete: function(result){

                // fires regardless of above





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


        $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

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

            echo 'No results have been loaded';