PHP: how to achieve asynchronous effect for server script - php

I have searched the internet and see people are working their way to make concurrent calls with PHP even though PHP doesn't have rich concurrency features. I recently want to make improvement on one of my scripts on the server side, which takes a request from a client, gets some data from the database, returns the data and does some other data update.
The problem now is that the client have to wait for the server to get the data, finish the update and everything else, then it can finally get the result that it asked for. The client however doesn't care about the data update that the server does and therefore should not waste time waiting for it.
Through my study all other people are talking about the client making asynchronous call to the server without waiting for result, but I want the server to return data to calling client in the middle of its process.
If I do not want to change anything on the client side, is there any workaround that can achieve this effect??

How about some pseudo multi-threading? http://phplens.com/phpeverywhere/?q=node/view/254

Related

Dynamic data updating

I'm making an app which accesses a database and updates the data every view seconds over a PHP script, the problem is that it currently always updates all data, I would like to know how to program something that dynamically updates data and decides what data to update and what not, so it basically keeps track of change somehow. So how would I best go along doing something like this ?
I think that there should be some where that this question has already be asked but I couldn't find it so maybe someone can show me a website where to look.
In general, you will need to user either XHR requests, web sockets, or HTTP/2 to solve this problem. Since HTTP/2 is not universally supported on the browser side, it may not work for you. Here is the outline of the solution:
Every few seconds, javascript you provide in the browser will need to poll the server for updates using an XHR request. You can use the returned data to update the screen with Javascript. If you only want to do some simple updates, like updating some numbers, you might use raw Javascript or jQuery. If your polling will result in complex screen updates or you want to move a lot of functionality into the client, you probably want to redo your client using one of the JavaScript frameworks like React or Angular.
Use web sockets (or HTTP/2) to create a persistent connection to the server, and have the server send updates to the clients as the data changes. This probably will require some code in the application to broadcast or multicast the updates. The client code would be similar to case 1, except that the client would not poll for updates.
The polling solution is easier to implement, and would be a good choice as long as you don't have too many clients sending polls at too high a rate - you can overwhelm the servers this way.

Should I use ajax for updating messages in a chat-client?

I am writing a simple chat-client (completely intended for learning purposes). My android phone sends messages to a remote MySQL database, and I am in the process of getting the browser to display any new incoming messages.
My current approach is using javascript: it calls a function every 5 seconds, which in turn calls a php that queries for new messages and sends it back to the browser.
I have no experience in ajax, but I've heard it is good when data has to change in a webpage constantly without having to refresh the page, which fits my situation.
My question is, does this sound like something I should use ajax for?
Yes, ajax is the way to go. However, what you have suggested (checking for messages every 5 seconds) generates a lot of requests and bandwidth. You should look into comet, which is still ajax but uses it in a different way.
Comet essentially is this:The client sends a request to the server. The php file on the server has a loop checking every few seconds for a message. When the server finds a message, it echos the message, but it doesn't close the connection. When another message arrives, it echos it again, but doesn't close the connection. This allows it to only need 1 request instead of hundreds. See http://www.zeitoun.net/articles/comet_and_php/start
I'll advice you to go for either ajax or websockets... if you're going for websocket, learn node.js... it has a lot of cool feature as platform built on Google Javascript V8 engine

php/javascript - using ajax to automatically update the client side

I am using PHP write the server side of the web page, and javascript to build the client side.
There is a div on the website that will show the data received from server side, for example, Let's say showing the current number of registered users in the databases. This number will keep changing in an unknown period of time. For example, the number could be the same in 10 hours, and it could increment by 1000 in 10 minutes.
My first question is, what is the best approach to do this functionality so that website can always show the latest or almost latest value of this data?
My original approach is using Javascript AJAX and wrapped by setInterval(1000) (-1 second) to send Ajax request to the server side. But I am not sure if this is too heavy for client side (because javascript is single threaded, it might be slow if there is a function running within each 1 second) or even server side( for example, if hundreds of users open this website and hundreds of requests will be sent to server side). So is this ok?
My second question is, if this is not a good approach, what else can I do to achieve the same goal. I was thinking about using the other way around. For example, if there is update in the server side, then use PHP in the server side to push this update to client side, or even directly change the data shown in the HTML using PHP scripting. Is this possible? if it is, is this a good approach?
Any codes or examples provided would be really appreciated.
You can certainly use AJAX for updates that are spread out over time, but if you want to connect to your server every second or so, I would advice against it.
You have a couple of options here:
As #Kay already mentioned, long polling might be an option.
Alternatively, you might want to look into WebSockets or a framework that supports WebSockets, like Meteor
You can use simple long polling.
The client side requests a script "/counter?oldvalue=...&timestamp=.... The server does not immediately return a value if it was not changed, but idles for up to 30 seconds.
If the counter value gets changed, then you return the updated value immediately.

Push data to page without checking periodically for it?

Is there any way you can push data to a page rather than checking for it periodically?
Obviously you can check for it periodically with ajax, but is there any way you can force the page to reload when a php script is executed?
Theoretically you can improve an ajax request's speed by having a table just for when the ajax function is supposed to execute (update a value in the table when the ajax function should retrieve new data from the database) but this still requires a sizable amount of memory and a mysql connection as well as still some waiting time while the query executes even when there isn't an update/you don't want to execute the ajax function that retrieves database data.
Is there any way to either make this even more efficient than querying a database and checking the table that stores the 'if updated' data OR tell the ajax function to execute from another page?
I guess node.js or HTML5 webSocket could be a viable solution as well?
Or you could store 'if updated' data in a text file? Any suggestions are welcome.
You're basically talking about notifying the client (i.e. browser) of server-side events. It really comes down to two things:
What web server are you using? (are you limited to a particular language?)
What browsers do you need to support?
Your best option is using WebSockets to do the job, anything beyond using web-sockets is a hack. Still, many "hacks" work just fine, I suggest you try Comet or AJAX long-polling.
There's a project called Atmosphere (and many more) that provide you with a solution suited towards the web server you are using and then will automatically pick the best option depending on the user's browser.
If you aren't limited by browsers and can pick your web stack then I suggest using SocketIO + nodejs. It's just my preference right now, WebSockets is still in it's infancy and things are going to get interesting once it starts to develop more. Sometimes my entire application isn't suited for nodejs, so I'll just offload the data operation to it alone.
Good luck.
Another possibility, if you can store the data in a simple format in a file, you update a file with the data and use the web server to check its timestamp.
Then the browser can poll, making HEAD requests, which will check the update times on the file to see if it needs an updated copy.
This avoids making a DB call for anything that doesn't change the data, but at the expense of keeping file system copies of important resources. It might be a good trade-off, though, if you can do this for active data, and roll them off after some time. You will need to ensure that you manage to change this on any call that updates the data.
It shares the synchronization risks of any systems with multiple copies of the same data, but it might be worth investigating if the enhanced responsiveness is worth the risks.
There was once a technology called "server push" that kept a Web server process sitting there waiting for more output from your script and forwarding it on to the client when it appeared. This was the hot new technology of 1995 and, while you can probably still do it, nobody does because it's a freakishly terrible idea.
So yeah, you can, but when you get there you'll most likely wish you hadn't.
Well you can (or will) with HTML5 Sockets.
This page has some great info about this technology:
http://www.html5rocks.com/en/tutorials/websockets/basics/

How do I implement observer pattern on PHP + Javascript/jQuery?

Just like in SO, where one is answering a question, if somebody has answered said question, a notification will appear (via AJAX?). My only way of somewhat replicating this is by including a timeout on my script that fetches if there is an update every n seconds. Is there a way to do this using observer pattern on PHP + Javascript (w/ jQuery)?
you have to look at the ReverseAJAX or COMET methodologies.
As per wikipedia
Reverse Ajax refers to an Ajax design
pattern that uses long-lived HTTP
connections to enable low-latency
communication between a web server and
a browser. Basically it is a way of
sending data from client to server and
a mechanism for pushing server data
back to the browser.
EDIT:
i suggest you to implement the following approach, this is simple to implement. I take stackoverflow answering as an example.
After the answer page load complete. Initiate a AJAX request (Asynchronos, so it wont block the UI)
And it will look for any new updates on the server side (polling the DB to check if any new answers added)
And return the data only to browser, if there is an update. otherwise stay calm.
After returning the data to client, client should invoke the another AJAX request and wait for the updates.
Repeat step 2 to 4 for the rest of the page life time.
Hope this helps.
If you use timeouts to query the server for updates, it may still be considered a peculiar implementation of the Observer pattern. Unfortunately, it's not possible to do it the other way around. If the server finishes responding to the main HTTP request, the client just finishes "listening" to it. The only way to do this is to make an asynchronous request from the client.

Categories