Retrieving updated information from database (PHP)

I'm currently working on a piece of code that pulls data from my database. However, I'd like this data to automatically 'refresh' every 5 seconds so that any new entries meeting specific criteria will appear without needing to refresh the entire page.

$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 exploring AJAX and PHP methods to achieve this, but haven't quite cracked it yet. Any tips or guidance would be greatly appreciated!

Answer №1

You can implement a solution like the following;

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

<script type="text/javascript">
    setInterval(function(){
        LoadContent(); // this function will be executed 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){
                // This will run regardless of the above
            }
        });
    }
</script>

In the PHP file that handles the Ajax request, you might have something similar to 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(!empty($aResults)){
        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 available';
    }
    exit;
}

Answer №2

Here is a simple example using jQuery to send AJAX requests:

<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)
      {
          //handle the response data here
      },
      error:function(e){
         console.log("An error occurred");
      }
    });
}, 5000); // Repeat every 5 seconds (5000 milliseconds) 
</script>

Answer №3

Here is an example using jQuery to load data dynamically:

<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 and set the data
    });
}

loadData(); // This runs on page load

setInterval(function(){
    loadData(); // This runs every 5 seconds
}, 5000);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting problem with jQuery autocomplete UI and JSON integration

I have been attempting to implement the jquery autocomplete UI, but have encountered issues. Unfortunately, I am not seeing a list of matches appear and instead, I'm receiving the error "TypeError: this.source is not a function." Initially, I added a ...

Retrieving information from an ImmutableMultiDict in Flask

I'm currently in the process of learning how to utilize ajax with Flask. My approach involves sending an ajax request and handling the data as a post request within my Python file. The code snippet in my HTML file: var data = {"name":"John Doe","age ...

Cleaning up database queries in MySQL without the use of prepared statements (PHP + outdated MySQL module)

Hello there! I recently came across an interesting issue regarding SQL injection in a PHP script that I downloaded called phpsimplechat. The author of the script created their own SQL layer which unfortunately turned out to be vulnerable to SQL Injection a ...

Unable to successfully add data into an SQL database using PHP

I'm encountering an issue while attempting to insert data into the 'products' table within my SQL server. Despite my efforts, the table remains empty and I'm unsure about what's causing this problem. Here's a snippet of my co ...

Alter information within jQuery AJAX success function

A sample function is provided below: jQuery.ajax({ type: "POST", url: jQuery("#exam_form").attr( 'action' ), data: jQuery("#exam_form").serialize(), success: function(result){ //Add row table.append(result); ...

What is the process for displaying the identification number in a descending sequence?

Utilizing PHP for exporting data from the database, I've implemented the following code which is functioning as expected. $sql = "SELECT `name`, `email`, `mobileno`, `data_of_added` FROM `emp` WHERE is_active=1 order by data_of_added DESC"; ...

Error parsing XML with SAX in PHP: memory exhausted at line x

Currently, I am utilizing the SAX Parser along with PHP to parse a 1.2GB XML file and save the results in a text file. However, after a few minutes, I encounter an error stating "no memory at line x". Surprisingly, the resulting text file is only a few kB ...

PHP - mysterious echo `<<<` operator

Recently I came across a PHP script with an interesting construct: echo <<<Start; I'm curious to know what this means - my initial thought is that it might be some form of redirection. However, I want to confirm the true purpose of this cons ...

Make sure to review the requirements listed in a comma-separated format

I am currently working with CodeIgniter and have a table where one of the fields can contain values like 1, 2, or a combination of both. Now, I need to implement a condition check in the model based on this field called 'period'. Model: if($po ...

What is the best way to retrieve these values using PHP?

I am trying to retrieve and print the following fields: Id, Nombre_del_paciente__c, Fecha_de_la_cita__c, and Hora_de_la_cita__c This is the result of print_r($response);: Object ( [queryLocator] => [done] => 1 [records] => Array ( ...

What is the best way to show a partial based on the variable in the index function of my controller?

I've been struggling to correctly display my partial based on the variable inside my index function. I've experimented with various approaches such as {{ $test }}, "test", and $test in the if statement without success. How can I resolve this issu ...

Displaying information stored in a database as notifications in the notification icon within the HTML/PHP header

Within my MySQL database, there exists a table named order_detail. This table is populated with values from my android app. I am looking to display the order_id as a notification in my admin panel, which is built using HTML/PHP. The attributes of the orde ...

Steps for storing div content (image) on server

Currently in the process of developing a web application that allows users to crop images. The goal is for users to have the ability to email the URL so others can view the cropped image, ensuring that the URL remains active indefinitely by storing every c ...

Trouble with $http response not appearing in AngularJS application

Currently, I am in the process of developing an angularjs application and encountering a challenging issue with setting up the $http connection to a php file. The header is displaying a response that I echoed from php. Nevertheless, two key problems persis ...

Receiving NaN in javascript when attempting to calculate the sum using a text input field

I am trying to calculate the total value by adding a fixed price with another value entered in a text input field. Here is the HTML code snippet: <%= f.text_field :hoursclass, id:"txt_hours" %> And here is the JS code snippet: $(function() { va ...

Retrieve information from a database by utilizing AJAX and store it in a JavaScript array

I'm facing an issue where I can retrieve data from the PHP file, but not from the database to my JavaScript code. I am using Ajax to fetch the data from the database, then passing it to the PHP file, and finally trying to filter this data using JavaSc ...

What is the best way to print a canvas element once it has been modified?

My goal is to include a "Print Content" button on a webpage that will print a canvas element displaying workout metrics. However, the canvas content, which consists of a visual graph of workout data, changes based on the selected workout (bench, squat, etc ...

Issue with Javascript/Jquery functionality within a PHP script

I have been attempting to incorporate a multi-select feature (view at http://jsfiddle.net/eUDRV/318/) into my PHP webpage. While I am able to display the table as desired, pressing the buttons to move elements from one side to another does not trigger any ...

When using form.serialize() in Django forms, an empty object is being sent

Upon clicking the button, my AJAX request is sending an empty object Object { } instead of form data. The form on my page consists of checkboxes and its HTML structure is as follows: <form method="post" action="" data-id="filter-form"> //Included ...

What is the best way to send a List in the model as a parameter for an AJAX request?

I'm currently using MVC 4 ASP.net with Razor views and I have an issue with refining my search results using AJAX calls. The current approach involves creating methods in the controller that include all the search filters, which has resulted in a meth ...