Instant MySQL Update from a PHP Page - AJAX? - php

Had a search, but nothing really suggests a good route for me (might be my bad).
I've built a system to be run on an iPad - and to work as a counter for people entering a venue. Essentially, it's a simple insert into a MySQL database from PHP of a record each time a button is pressed on a web page.
That is, when someone enters the venue, a person on the door presses "In" when someone leaves "Out", an 'in time' is inserted into a MySQL database, and an 'out time' so at any time we can find out how many people were in the venue.
Simples. However, of course, it's quite slow, when multiple people are entering the venue at any one time, so I was wondering how you guys would deal with this. I've looked at AJAX, and I must admit this isn't really my field, but I've had a play. I'm naturally concerned about not losing any data, but also, we can't have the system waiting for 10 secs to reload the page.
My original idea was to have an AJAX 'thing' - which when the 'IN'/'OUT' button is pressed, it calls another PHP page to do the MySQL insert. Is this sensible? Or is there a better way of doing this? As my concern with the AJAX solution is that a new call of that 'insert.php' page, would cancel execution of a previous one, so data may get lost? Am I right?
Any insights anyone has would be VERY helpful.
Thanks in advance.
Ryan

You can achieve this easily using jquery.
First post data from main file and catch data in another file using $_POST['message'], to acknowledge data saved successfully you can output json. Here is example
On your html or php page
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#send_data").click(function(event){
var message= 'This is my message';
sendtodb(message);
});
});
function sendtodb(message){
$.post("save.php",{message:message},function(data){
alert(data.status);
},"json");
}
</script>
Now on secon file where you will save data:
<?php
$msg=$_POST['message'];
mysql_query("insert query");
json_encode(array('status'=>'data saved'));
?>

You'd probably be better to have more than one button on the layout, something like:
IN: 1 2 3 4 5 6 7 8 9 10
OUT: 1 2 3 4 5 6 7 8 9 10
It'd save on the number of requests being sent (and the need to press the same button 10 times).
Other than that, Ajax might be an idea, but you'd need some output to the user so that they know their press of the button has actually done something (as it's not refreshing the page, it's not obvious its doing anything).
But if it's taking that long to reload the page, then the bottleneck might not be because the page is reloading - it could be that the server is getting overloaded with requests (which doing my suggestion above should reduce), or could be the result of some badly written code taking a while to execute.

I think using AJAX is the way forward here, and jQuery does indeed make it really easy. Just a few extra thoughts and ideas:
Potentially a race condition could occur if a user keeps clicking before the ajax request has actually completed, particularly if the server becomes overloaded. I would do what Google search does here, and make sure you keep a record of the previous AJAX request and cancel it when a new one is launched, see this other post
With your back end PHP script, I reckon it's quite likely that this will form part of a larger PHP application. Try to make sure that any other processing that might be done for the front end site, such as building menus for example, isn't done on an AJAX request, because you don't need it and it just wastes processor time.
For more robustness, send a return value from your PHP script which maybe includes a status code, so you can detect if the call actually completed.

Related

Can you have a timer for SQL or PHP?

So i've found options but they're not suitable. Im currently making a PHP browser game which uses an SQL server.
Im trying to figure out a way for when the button is pressed, after 300 seconds an SQL cell should update and during the 300 seconds for it to be displayed on screen. Doesn't have to be a count down, even whats left.
Figuring out a way to do the 300 seconds and have it displayed when refreshed is what im having trouble with.
If you can get away with the potential problems that may arise if the user closes your application's browser tab, your best option would be a JavaScript snippet to do it:
When the user clicks the button, lunch a JavaScript timeout like this
// 1. prepare timeout
setTimeout(on_timeout_fn, 300000);
What this piece of code does is, after 300 seconds, it will call on_timeout_fn function.
When time is up, your function on_timeout_fn will execute. You should define it to something like this:
let on_timeout_fn = function() {
// 2. run an ajax call to execute a PHP script that will update the database
// if you're using something like JQuery, it should be as easy as:
$.post("update_db.php", "data_to_send", function() {
// 3. when ajax call ends, make sure the button dissapears
$("#yourButtonID").toggle();
}, "text");
}
Well you would have to do this with JavaScript, and PHP. You can also use JQuery to do this feature. In Javascript you would grab the button on by its query selector wether that be an class or id by clicking and then you could set an a timer to where it won't execute the code until 300 seconds, then it runs the code sends the value to the back end by AJAX, fetch whatever you prefer. Then proceeds to use use PHP and MYSQL to update the data.
No, it doesnt exist really, not in 'standard' code. You can aproach it some other way though:
On click you update the database, you set an eg timerReady to NOW()+300sec.
On refresh/reload/cron/whatever you check if timerReady < NOW(), then you know the 300sec have past. Otherwise, timerReady - NOW() is the amount of second remaining.
When you press the button you let javascript wait 300sec (I do recommend a timer/indicator) and then reload. And when the user reloads in the meantime, you can use the timerReady - NOW() trick to decide how long the user has to wait still.
You can do this with Javascript only, but if you do not store it in the database, when a user refreshes they must start over as you have no way of verifying anything.

Show DIV before refresh

I have a webpage that is auto-refreshed every 240 seconds with the generic HTML Meta tag. During the refresh it pulls data from a database which takes the site about 15 to 20 seconds to build before it's shown to the user. During this time I wish to show a small DIV with a loading message telling the user that it's loading data.
The more complicated thing about this is that the user has a few menu options to filter out specific data from the database. When clicking such an option the page is reloaded again and takes 15 to 20 seconds to build.
Users that aren't familiar with this loading time might feel the need to click the same menu option over and over again within a few seconds hoping that the page will load faster. But instead it will most likely cause the database server to get overloaded with requests.
So, to tackle this I wish to use jQuery to show a loading message, then have it load the data from the database (with a PHP script) and finally dump the data on the page.
I've done something similar but that was limited to users clicking a link which caused a jQuery script to load the data while showing the waiting DIV (using CSS rules).
I can't figure out how to implement this solution for an auto-refresh.
Some help would be nice.
You can use the same solution with auto-refresh as well, with the mention that the initial page load doesn't container the data that requires the DB call, but instead shows a loading message and starts an AJAX call to a server side script that returns the data.
Your page load:
Request
Server query DB
DB Response
Page loads (with data)
Ideal page load:
Request
Page loads (without data) <- loading message here
AJAX call
Server query DB
DB Response
Page updates (with data)
I'd second megawac's comment. Don't use a meta refresh. Also, 15-20 seconds is a very long time for generating a database report that is going to be generated every 4 minutes; odds are that you're bogging down your server pretty badly. Very few queries should really take that long, especially queries that need to be run nearly continually. I would strongly recommend refactoring your queries or doing some caching to speed things up. If you post some code, I'm sure people would be happy to look at it.

pre-loaded content; not requiring Internet access to display new content onclick + mysql submission if connection OK

First some background:
I've developed an informal feedback system for disabled learners that collects data and periodically emails out the results as percentages with piecharts.
QTV http://www.mwjt.co.uk/QTV.jpg
Currently it uses 2 PHP webpages:
-The first reads the question from the database.
-The 2nd (a thank-you page) takes the input (as GET) and submits it to the database and then redirects back to the first with an arbitrary random string variable to force full reload (to make sure it's displaying the latest question from the database; these are updated manually using email).
Unfortunately the system is on a wireless connection that occasionally drops. As a result, when a student hits the switch input, a 'no Internet connection' is displayed and then sits there until I remote in and hit refresh.
My question is this:
I'm looking for the best workaround for this dropping connection. I'm not fussed if some entries are not submitted to the DB when the connection is down (it is informal and not totally accurate after all), but I'd always like the cycle of hit a button -> thank-you page displayed -> redirect to question (with check for new question if connection OK, else display previous question) to be consistent.
I'm assuming I somehow need to have both the question and thank-you loaded in one page and have no errors thrown up if submission fails, but I don't know how to proceed.
Many many thanks, Mike
On the first page, when they select any of the choices, have a simple div the size of the window pop up and cover the whole page so it looks like another page. Write an AJAX script (in the HTML itself) which executes in the background to submit the data. If the internet fails, the AJAX probably will fail, but since the script for the popup is local and has loaded with the HTML already, it should still work.

PHP autoupdate form data without pageload

I run a php script game site, and there's a section of it where a player can distribute his 'skill points' in 'Attack', 'Defence', or 'Stamina'.
At the moment, it's just a basic HTML/PHP form with a + next to each stat, so if the user had 100 points and wanted to put them all into ATTACK, he'd have to click (and pageload) 100 times. Obviously that's silly.
I want to be able to make it so the player can distribute them (without page reloads), then finally click SUBMIT once he's happy with it.
Could anyone point me in the direction of what I need to do this? Is it some ajax or javascript? I suppose I could do form fields and clicking the PLUS would increment each field..
It sounds like you need an onclick() to call a javascript function for the plus button, that increments the value in javascript, updates on the page and checks that the user has distributed the points correctly (i.e. distributed 100 points or under in your example) and then have another button at the bottom of your points distribution that sends the data to a PHP page that handles the storage of the values.
If you wanted you could then use ajax to send that data to the PHP page without having to reload the page. I've found the W3schools site adequate for teaching basic ajax usage: http://www.w3schools.com/ajax/default.asp
(But remember to check the user input on the server side as well, don't trust user input!)

Using jQuery.post() to submit content and display what's going on

This is more of curiosity that anything, but I can think of several places (mainly in admin sections) where this could be useful. I know the title is confusing so this is what I mean:
Say you have a form that posts to example_cb.php. example_cb.php is a very large callback page that generates multiple thumbnails of an image, puts them in their respective directories, adds them to a database, etc. You already have the form posting by jquery with a function like this
$.post('example_cb.php', $(this).serialize(), function(data) {
// Success
}, 'json');
Before posting it updates a div to say "processing" of something. Then after it successfully completes the div fades out. However you want the div to show what is happening on the server side. i.e. Converting 200X200 thumb > Converting 350x350 thumb > Adding Records to Database > etc.
How can you accomplish this?
I know it's a loaded question, but I'm confident there are people on here smart enough to figure it out. If you need more info please comment :)
You could do something like -
Write each 'event' update to a database table
Write a page that retrieves the last n events from table
Use something like 'load' to call page update an onscreen div
with the updated progress.
Use 'setTimeout` to keep updating.
This could be accomplished most easily with using the push method, but I'm not too familiar with ajax push or comet technology, so I'll give you a pull solution.
Basically you need to create the initial ajax request to start the processing. Then, you need to have another request running in a tight loop that checks against a php page for the current status. For example, on the php page doing the processing, you can update a _SESSION key that stores the current processing information (like "Converting 200X200 thumb") at each step. Another php page will exist purely to print that information and you can retrieve it with the JS running in a loop.
pusher like services may be used for bi-directional communication.
I'm putting it down for reference, though this would be overkill for such a simple scenerio.

Categories