Viewed   84 times

In my own system, I have a PHP page which displays all the goods I have sold through my online webshops, from the latest transaction to the first.

I would like this page to automatically update, whenever people buy something from me.

I could make AJAX call every 5 seconds to check the orders in my databases, but that seems 1980? or is it that way people do it?

How can I go about pushing a notification to my php page whenever my php newOrder() function (lets call it that) is called?

 Answers

4

You can achieve push within PHP but it won't be the most efficient solution because to achieve push you need to maintain long running connections between your client and your server (HTTP or WebSocket connections).

See:

  • Long Polling/HTTP Streaming General Questions
  • phpwebsocket
  • php-websocket on github
  • Ratchet
  • how to implement comet in PHP - frequently linked to guide

General best practice when building a realtime infrastructure has been to decouple the push solution from your web application (Note: node.js and socket.io has changed this a bit, but personally I still think it should be decoupled). But, assuming that the latter is still the best solution you would need to write/host/install this push solution. Decoupling also means that the technology doesn't have to be PHP but you can access/use it from PHP. Maybe a bit of overkill? And especially if you don't have too many users on your site?

For simplicity I would recommend looking at using a 3rd party hosted service. I work for one such company called Pusher. Using a service such as ours lets you remove the need to install and maintain the realtime part of your application. It also makes it really easy to add the push functionality you are looking for. All you need to do is add a few lines of PHP code to your existing app to trigger the push notifications and add a few lines of JavaScript to your front-end.

Resources:

  • Most commonly use PHP library for this: https://github.com/pusher/pusher-php-server
  • Quickstart guide

If you'd like to investigate the alternatives or some of the technologies I've mentioned above I'm maintaining a list of realtime technologies which you might also be interested in.

Sunday, November 20, 2022
4

If I understand what you want to happen then this is how I'm implementing it. It's in Prototype instead of jQuery but it shouldn't take you long to translate:

new Ajax.Request('process.php', {
    on401: function(response) {
        var redirect = response.getHeader('Location');
        document.location = redirect;
    }
});

In your PHP, output the following if the session is inactive:

header('Location: http://example.com/login.php', true, 401);
exit;
Monday, September 19, 2022
 
3

You cannot push data to a browser, but what you can do is set up your webpage to poll your server every few seconds for updates. An example setup would be:

From within your website, have a javascript function that runs on a timer every few seconds (or whatever interval works best for your situation).

Start that timer on page load.

That javascript function invokes an AJAX call to a web service on your web server (more on that in a second).

On the server side you'll need some sort of system that tracks these events and stores them somewhere such as in a database table with a timestamp. So for example when XYZ creates an account, that would be logged in this "event" table in the db.

The web service called by the AJAX call will then run a query on that table and retrieve all entries since the last time it was called. Then just update the webpage with those results.

It's obviously not 100% "live" as there will be a small delay depending on what time interval you set in the JS timer but it's pretty close.

Thursday, September 22, 2022
3

Here are some good ones too:

http://www.frozenmountain.com/websync/demos

Saturday, November 12, 2022
 
furq
 
3

Thank you all for your inputs. I figured out a way to make it work.

I wanted to be able to send the data to the datatables within a jquery callback because this would allow me to create my own search outside the datatables. The way I've done it is by running an ajax call that performs the query to the database and then I pass the results of that query to the datatable but the issue was how to format the data in a way that the datatable would accept and how to make it read that data to display on the table.

Simple ajax call and populating the datatable

This code can be further modified (which I will do in my case) but it should give you an idea of how to accomplish what I've been wanting to do. (it works btw).

<script>
$('document').ready(function()
{
    $.ajax({
    type : 'POST',
    url  : 'test.php',
    dataType: 'json',
    cache: false,
    success :  function(result)
        {
            //pass data to datatable
            console.log(result); // just to see I'm getting the correct data.
            $('#test_table').DataTable({
                "searching": false, //this is disabled because I have a custom search.
                "aaData": [result], //here we get the array data from the ajax call.
                "aoColumns": [
                  { "sTitle": "ID" },
                  { "sTitle": "Name" },
                  { "sTitle": "Email" }
                ] //this isn't necessary unless you want modify the header
                  //names without changing it in your html code. 
                  //I find it useful tho' to setup the headers this way.
            });
        }
    });
});
</script>

test.php

This is the simple version I used for testing. My actual code is much more larger as it has several parts for querying and searching.

<?php

$columns = array( 
// datatable column index  => database column name
    0 => 'id',
    1 => 'name',
    2 => 'email',
);

$sql = "SELECT * FROM test_table";
$res = mysqli_query($conn, $sql) or die("Error: ".mysqli_error($conn));
$dataArray = array();
while( $row = mysqli_fetch_array($res) ) {


    $dataArray[] = $row["id"];
    $dataArray[] = $row["name"];
    $dataArray[] = $row["email"];

}

echo json_encode($dataArray);

?>

This simplifies things a lot, at least for me. I did not want to include additional libraries 'ssp.class.php'. I also did not want to get into PDO. So this has made it a lot more flexible and I hope it helps others who are trying to accomplish something similar.

Friday, November 11, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :