I have a service running on a pc witch does some inserts in my (MySQL) database. What I want to do is everytime a new record is inserted in database to refresh automatically my webpage (I am using php). I read a relative post about updates
refresh the webpage on database update, but those updates were done "from" the webpage.
I also read another post
https://stackoverflow.com/questions/6460297/automatically-refresh-the-webpage-just-after-a-new-database-entry, didn't figure out how I can do this.
Any suggestions?
This is how you do it
Use JavaScript's settimeout() function to run an ajax request to your server at a set interval in which you send the id of the last record on the page. The use Javascripts window.location.reload() function to reset the page if the last record's id is different.
Why you don't want to refresh the page
This is bad user experience. You don't want the page refreshing out of no where. The best idea is to send the latest id on the current page to the server and check for any new ids. If there are new ideas send the records back via json and append them to the end of your results table.
This scenario is some complex but possible solution of your requirement!
In our scenario we have developed a sms-gateway and defining a trigger when ever any record is inserted we call a function that sends a sms to our gate way that behind that gateway we have developed our page. :)
In other way by defining timing ajax or many other ways where some what how our some resources are used, we have to compromise.
Ideally you want to trigger an update of data on the page via AJAX as opposed to a full page refresh. You can potentially accomplish this using web sockets. A popular server-side implementation is socket.io. Which uses the nodejs environment.
You could potentially write a MySQL UDF which executes in your trigger and signals nodejs to push more data (which may require writing a nodejs package as well). So, not trivial, but definitely doable :)
Related
I am developing a PHP web app with jQuery and Twitter Bootstrap. And it uses AJAX for everything. So, I show a form in HTML5, the user press a button (class="btn"), the form is sent to PHP (jQuery, AJAX), PHP makes a query to the MySQL and echoes an answer, which is shown in the form (jQuery). This is basically how the web app works.
But here's the deal, the first form it is showed, it's a div that shows some news. For example:
A new user was created.
There is new important date.
Someone wants to text you.
So I've created a table in MySQL called News where I saved some values than mean something like:
1: A new user was created
...
Everytime the user log in will se that. It means that there will be a query and a response as soon as the HTML5 get loaded when a user log in.
The index.html file has a navbar (Bootstrap), and a option call News. When the user clicks it, the same query will be executed, but not necessarily the same response.
I thought in modifying the div with news whenever the user does an action. But, an action can also be done by another user. So it is necessary to make the query again!
Is there any solution that allows me to avoid querying the database when the user wants to get the news? Or how can I know that it is necessary to update the div right now? I was taking a look at caching queries but didn't arrive to a conclution.
Sorry if my english is not too good, it is not my native language.
Thank you.
You can send a timestamp in every news response from the server and save it in javascript. The next time you make a request, send the timestamp you saved and the server checks if there are more recent news, sending nothing if there is none as the last response is still the newest.
Well, there is a downside here, you still need to make a query to the database (filtring the results with a WHERE clause like 'WHERE ... TIMESTAMP > last_timestamp_from_browser') which is perfectly valid, SGBDs are designed for this, and if you don't have thousands of users accessing your website at the same time there will not be any problem. With this approach you will only save bandwitdh as the connection to the database is still made.
There is another way that prevents this connection from being made, cache some values of last news inserted which could be user specific or global and save them in APC module (or memcached). You'll need to discover what to cache and when (you can't cache the entire database, just some well organized timestamps and maybe the most requested news for example). This way you prevent the database connection from being made. This will force you to do many many more code, so, use it only if you really need it, like thousands of user connections at once.
So the question is a little complicated, let me explain. My page code is running like this:
User enters query in the search field and clicks submit.
1.1 jQuery loads a new body to display progress data.
1.2 jQuery calls process.php via AJAX and supplies query as the argument.
1.3 jQuery starts setInterval periodic update to grab progress data, stored inside $_SESSION['prog'], and displays it.
When process.php finishes, jQuery stops periodic update, displays final information and calls AJAX to clear the $_SESSION['prog'] variable.
At the moment progress data is stored inside one variable, which is fine as far as different users are concerned (because of the different sessions), but if the same user were to make multiple requests at the same time, the $_SESSION['prog'] variable would be cross-overwritten.
So far I have thought of two possiblities to distinguish data for each request from the same user (same session)
Have jQuery generate some random string and send it together with query (and hope to avoid colission, although that would be unlikely)
Make 2 AJAX calls, first one requesting new_request_id, the second one sending query and new_request_id as parameters.
Have AJAX return something from PHP before is finishes(completes).
I need to connect each browser window (each request) with each running process, so I cannot send back new request ID after the request has been submitted, because I wont know which data to pick up with jQuery in the browser window. Btw, I will change $_SESSION['prog'] to $_SESSION[request_id] -> request_id is what I'm looking for.
It (request_id) could be last_insert_id(), because im creating new DB entries for each valid query, but I don't know how to get it back to each different user window.
I need advice here. Only just begun to code in PHP, AJAX and jQuery, don't really know much about sessions. How should I solve this problem?
Sorry for the lack of code, I will paste is at request.
You could add a unique ID to each request in addition to the session ID. eg. uniqid() in javascript/jquery?
You need to differentiate them somehow. For example use a unique ID autonumber field. MySQL has last_insert_id() which is very useful and handles concurrent requests correctly.
Avoid using Session variables in Ajax requests. Send them with GET (or POST) instead. Even if calling Session_start(); in the Ajax request and getting $_SESSION['prog'] from there, results can be unexpected.
I'm making a small php game for school. It has to be some kind of multiplayer game called four in a row/four in a line, whatever you want to name it.
Because its a multiplayer game and my playing field is saved in a database, I want to refresh the 'gamefield' if a user is making an action on the page. Like if he inserts a chip in the field, the other user must see it as well, and they have to switch turns. So how can I refresh the page on both computers/browsers when only 1 person is making an action on that page? So that both computers/browsers see the newly inserted chip in the field and the switching of a turn?
The web server usually do not initiate connexions to the browsers. You can check periodically from all computers/browsers if the state of the game changed. Ajax probably fits your need.
Use setTimeOut() or setInterval() to call a function, which makes a AJAX request for a field update. I would also advise to use jQuery to avoid writing everything from scratch.
I successfully send data from Android to PHP and store in MYSQL database.
What I want is to display the data in my PHP page automatically without refreshing the page when data has been sent from and Android device.
Is this possible, possibly using jQuery with AJAX?
Please explain how it can be done or point me to a resource where I can find such information.
So you essentially want to update the page when data changes on the server.
Two main options come to mind:
1. Ajax poll
Use setTimeout in conjunction with an ajax call to periodically call the server and see if anything changed. You already mention jQuery, that's certainly a good place to start. Get familiar with http://api.jquery.com/jQuery.ajax/. This is probably going to be your best bet.
2. PubSub
I use http://www.pubnub.com/ on one of my sites for this very purpose. The browser subscribes to a pubnub channel, and the server publishes on that channel anytime something changes on the server. This is obviously more work to get setup up front, and more applicable for rich client-side applications (mine is a single-page app).
There are plenty of other implementations of PubSub as well.
I would like to find a way to have my user not having to wait for the output of a php script and being redirected to a page while the script is running on the server.
Basically the user submits a form which takes quite long to process and I would like to redirect the user to a page notifying him that the form is being processed and that its output will be later available (I thought about opening a tab when the output is ready).
Basically I would like something like this, which I tried without success, the
if ($form_valid) {
process_form(); // this would need not to be running on the current page so that the user don't have to wait for it to be ready (timeout problems)
header('Location: http://example.com/form_submitted_output_coming_soon.html');
}
I hope that it is not too vague.
Thank you in advance for any help / advice on how I could do that.
It really depends on the time the script takes to execute if it's seconds, under 10 I would do an ajax request and have a modal progress message
If they take extended amounts of time my approach would be to create or use an existing task scheduler/ report generator
a single system scheduled task entry calling a central management script ( probably not optimal )
You mark a task/report for execution
Concurrency. Count, limit the number currently executing ( so you don't over load the server)
users pool via ajax for their tasks / reports or push to the clients with web sockets
Example on how to fork php to background
Update
I think you would get better performance out of a bot continuously check a database or file for work to do and submitting results back to the database. Alerting users via ajax, web sockets and or email when the work that they need is done / updated.
Here is a good introduction on how to build a web crawler in php
The best approach for solving this kind of problem is to use AJAX to make the request to the server in the background and then update the user once it has finished processing.
You may submit the form with an asynchronous request (ajax) and handle the page forward also with javascript. This way your form is handled asynchronously - you may even wait for the response to tell the user once you have an answer. This asynchronous request will not block the UI.
Just for completeness if you really really want to use php only for this:
Run PHP Task Asynchronously