Ajax push system - php

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?

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.

You could simulate a push effect by doing the following (pseudo code!)
// This would go on for 60-90 seconds, unless there is new data
for($i = 1; $i <= 60; $i++) {
// Check in the database what the last timestamp is
// Compare this to the timestamp that has been posted by the AJAX-call
// If there is something new, show the data and then exit
// If not, sleep for 1-3 seconds
}
Your javascript:
function pollForNewProducts() {
// Check if there is a timestamp
// Make an AJAX-request to the script that has the first code in it
// If there is a response (JSON?) than evaluate that
// If not, then run the script again
pollForNewProducts();
}
It is a simple yet effective way to let the server do all the hard work, instead of timeouts on the client side which will cause the browser to eat memory.
More about this on:
Simple “Long Polling” example code?
Client notification, should I use an AJAX Push or Poll?
PHP or Javascript poll code
ExtJS 3.0: Ext.Direct with PHP: Polling:ok and Pushing ?
Comet Programming: Using Ajax to Simulate Server Push

Apart from the excellent suggestion about nodejs ..if you want to still use php to achieve this, you want to look for the COMET method, not ajax.
Howto with php here : http://www.zeitoun.net/articles/comet%5Fand%5Fphp/start

Related

How to process massive data-sets and provide a live user experience

I am a programmer at an internet marketing company that primaraly makes tools. These tools have certian requirements:
They run in a browser and must work in all of them.
The user either uploads something (.csv) to process or they provide a URL and API calls are made to retrieve information about it.
They are moving around THOUSANDS of lines of data (think large databases). These tools literally run for hours, usually over night.
The user must be able to watch live as their information is processed and is presented to them.
Currently we are writing in PHP, MySQL and Ajax.
My question is how do I process LARGE quantities of data and provide a user experience as the tool is running. Currently I use a custom queue system that sends ajax calls and inserts rows into tables or data into divs.
This method is a huge pain in the ass and couldnt possibly be the correct method. Should I be using a templating system or is there a better way to refresh chunks of the page with A LOT of data. And I really mean a lot of data because we come close to maxing out PHP memory and is something we are always on the look for.
Also I would love to make it so these tools could run on the server by themselves. I mean upload a .csv and close the browser window and then have an email sent to the user when the tool is done.
Does anyone have any methods (programming standards) for me that are better than using .ajax calls? Thank you.
I wanted to update with some notes incase anyone has the same question. I am looking into the following to see which is the best solution:
SlickGrid / DataTables
GearMan
Web Socket
Ratchet
Node.js
These are in no particular order and the one I choose will be based on what works for my issue and what can be used by the rest of my department. I will update when I pick the golden framework.
First of all, you cannot handle big data via Ajax. To make users able to watch the processes live you can do this using web sockets. As you are experienced in PHP, I can suggest you Ratchet which is quite new.
On the other hand, to make calculations and store big data I would use NoSQL instead of MySQL
Since you're kind of pinched for time already, migrating to Node.js may not be time sensitive. It'll also help with the question of notifying users of when the results are ready as it can do browser notification push without polling. As it makes use of Javascript you might find some of your client-side code is reusable.
I think you can run what you need in the background with some kind of Queue manager. I use something similar with CakePHP and it lets me run time intensive processes in the background asynchronously, so the browser does not need to be open.
Another plus side for this is that it's scalable, as it's easy to increase the number of queue workers running.
Basically with PHP, you just need a cron job that runs every once in a while that starts a worker that checks a Queue database for pending tasks. If none are found it keeps running in a loop until one shows up.

notification system in PHP/jQuery

I want to program some sort of notification system. What would be the be the best way to achieve this?
By calling Ajax request call to database on page load? But the problem with this is that it only checks on page load. It would be better if it was even realtime, I guess that depends on the priority of the message. How would I go about on achieving this?
By using cookies?
I am using PHP and jquery.
Like you said, it depends on message priority.
If notifications are made upon the visitor performing an action, it would be easy to tie in session-based notifications.
If notifications are made upon other users performing an action (e.g. "John made an edit to this page. Click here to view."), you could use long-polling AJAX to wait for a notification.
You might wanna look into COMET programming.
This would most likely require you to implement this as a distributed solution depending on your traffic.
Basically you'll have a java script function that goes to a server to check for notifications and if it finds any, calls another script that fetches the notifications back to the client. This should happen every so often, and WILL create a higher traffic and leave more connections open.
Take a look at this thread: Using comet with PHP?
For something small, I would consider using setInterval in combination with jQuery .load to load JSON.
Well AJAX and Jquery can be used to develop basic notification system. I've implemented it completely here: http://www.cloudways.com/blog/real-time-php-notification-system/
You can follow it step by step and also scale it as per your requirements.

Any idea how to implement this?

Any idea how to implement this (http://fluin.com/63) using MySQL+PHP+Javascript(mootools)?
In a nutshell, it's a realtime threaded conversational web app.
Update:
This uses http://www.ape-project.org/home.html
Any idea how to implement realtime stuff without AJAX push (ape)?
Install Firefox.
Install Web Development toolbar
Install Firebug
Install HttpFox
Read docs of above tools re how to use, what they can do.
Go to http://fluin.com/63. Use above tools to inspect.
Read up on Databases and data models, and MySQL.
Build your own.
Well, this depends on your definition of realtime, which, in its technical meaning, is simply impossible with public ip networks and traditional tcp stack, for you have no control over timing.
Closer to the topic though, to get any web page updated without direct user intervention, you'd have to use javascript to poll server for changes since the last successful poll, and do this over certain intervals of time. In calculating these intervals you'll have to consider both network/server load, and the delay that is comfortable for the user.
The server, of course, will have to store the new data and its timely status (creation timestamps are one way of doing it), to be able to distinguish between content already delivered to various clients.
As soon as the server reports new content, it is inserted into a dom page via javascript and the user sees the response.
This is a bit general, of course, but you should get the idea.
Isn't it like a shoutbox ? here an example of one
Doing this properly using PHP only is very hard. When you have 5 users you could use long-polling, but it will definitely not scale when you have let's say 1000 users.
Using comet with PHP?
The screencast(link) in my post shows how you could implement it, but it has a couple of flaws:
It touches the disc(disc is very slow compared to memory).
To make matters worse it also polls the disc frequently(filemtime()).
Maybe phet(PHP) is able to scale. You should try that out.
To make it scale I think you need at least:
a good implementation of long-polling(at least long-polling. You have better transports) that can handle load.
keep data in memory(much faster than dics) using something like redis or memcached.
I would use:
node.js with socket.io(video) module.
to keep data in memory I would use node_redis(video).

Push notification to the client browser

I'd like to create an application where when a Super user clicks a link the users should get a notification or rather a content like a pdf for them to access on the screen.
Use Case: When a teacher wants to share a PDF with his students he should be able to notify his students about the pdf available for download and a link has to be provided to do the same.
There are several ways you can accomplish this. The most supported way is through a technique called Comet or long-polling. Basically, the client sends a request to the server and the server doesn't send a response until some event happens. This gives the illusion that the server is pushing to the client.
There are other methods and technologies that actually allow pushing to the client instead of just simulating it (i.e. Web Sockets), but many browsers don't support them.
As you want to implement this in CakePHP (so I assume it's a web-based application), the user will have to have an 'active' page open in order to receive the push messages.
It's worth looking at the first two answers to this, but also just think about how other sites might achieve this. Sites like Facebook, BBC, Stackoverflow all use techniques to keep pages up to date.
I suspect Facebook just uses some AJAX that runs in a loop/timer to periodically pull updates in a way that would make it look like push. If the update request is often enough (short time period), it'll almost look realtime. If it's a long time period it'll look like a pull. Finding the right balance between up-to-dateness and browser/processor/network thrashing is the key.
The actual request shouldn't thrash the system, but the reply in some applications may be much bigger. In your case, the data in each direction is tiny, so you could make the request loop quite short.
Experiment!
Standard HTTP protocol doesn't allow push from server to client. You can emulate this by using for example AJAX requests with small interval.
Have a look at php-amqplib and RabbitMQ. Together they can help you implement AMQP (Advanced Message Queuing Protocol). Essentially your web page can be made to update by pushing a message to it.
[EDIT] I recently came across Pusher which I have implemented for a project. It is a HTML5 WebSocket powered realtime messaging service. It works really well and has a free bottom tier plan. It's also extremely simple to implement.
Check out node.js in combination with socket.io and express. Great starting point here

How to run my php code in every X minute?

i try to make a "status monitor" for our small network. After the page was load i make a ping for every IP which i addedd. Its, ok. But i would like to do this ping in every X minute, without reload my hole page.
I can make it if i reload the page with header refresh, but i would like to do this witout reload.
I think i have to do this with AJAX?, But i dont know how..
Thank you
I would strongly suggest you have a look at Nagios or something similar:
1) you don't need to have a web page constantly open to detect problems
2) it can automatically verify and escalate issues
3) there are lots of probes available out of the box which can be used to measure all sorts of things - not just ping times
4) responding to a ping is not the same thing as working
5) it automatically collates stats to identify patterns of issues
6) it also provides SLA type reporting
7) Nagios is simple enough that even I can understand it
8) its what I chose after a lot of work researching a replacement for a system similar to you are suggesting.
HTH
C.
If it is entire code of page i suggest setting up a cron job
and if you want to use ajax ( ie jquery ajax there is a plugin called jquery timer) use it send a ajax request to the page with code you want to run.
http://plugins.jquery.com/project/timers
check this out
I suggest you take a look at some of the "other-way-around" approaches, such as COMET, here is an interesting article covering basic usage with PHP.
This would put the implementation of "ping" in your server instead of the client.
You could for instance instead of setting a fixed interval push out updates at will. Meaning you would get almost realtime status notifications instead of the fixed interval updates.
In web development, Comet is a
neologism to describe a web
application model in which a long-held
HTTP request allows a web server to
push data to a browser, without the
browser explicitly requesting it.
Comet is an umbrella term for multiple
techniques for achieving this
interaction. All these methods rely on
features included by default in
browsers, such as JavaScript, rather
than on non-default plugins.
COMET (Wikipedia)
Why don't you try a cron?
I'm not sure exactly what you want to do here, but this quick tutorial shows you how to call a php file every second and update a dib block with the results. It is quick and simple using jquery.

Categories