0

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!

1
  • Kind of threw my rubbish away.. But what I've tried is put this in a function and then call the function each 5 seconds in JQ, for some reason it didn't work.. @KoenHollander (Ik versta ook nl...) Commented Nov 18, 2016 at 10:31

3 Answers 3

1

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;
    }
Sign up to request clarification or add additional context in comments.

8 Comments

Could you convert this into something that uses time to do this? Because this is something I can do too, the timing stuff is something I don't understand :) @atoms
@atoms Before I try this and tell you it doesn't work, are the value and value2 the names of my vars in php?
no they are javscript vars. Left it there to illustrate how you can post data to php.
just tested code and its working (updated). Just change the url path
Thanks for your patience and help! Really made my day!
|
0

Using jQuery:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
setInterval(function()
{ 
    $.ajax({
      type:"POST",
      url:"path/to/script.php",
      success:function(data)
      {
          //do something with response data
      },
      error:function(e){
         console.log("Error Occurred");
      }
    });
}, 5000);//time in milliseconds 
</script>

Comments

0

Using jQuery you can try something like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 

function loadData(){
    $('#table').load('yourScript.php',function (response, status, xhr) {
         // handle the response here and set the data
    });
}

loadData(); // This will run on page load
setInterval(function(){
    loadData(); // this will run after every 5 seconds
}, 5000);

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.