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.
Related
I am not hoping for fully working examples, I am just in need for a direction to start.
So to explain what I am trying to do, I have an app where users log in, log out, add content, do actions in the site etc. I want to know if it is possible using PHP and AJAX to make a widget that auto updates like this:
Someone logged in...
Someone added photo...
etc..
I just want a guideline or direction to follow, how would I make real-time widget that auto updates and pull data/actions/etc.. would it be time interval update?
Any ideas?
First of all you need to store a list of actions that you want displayed in the widget, for example you can create a database table with (id, created_at, action_description) and whenever a user performs an action that should be displayed in the widget (e.g uploaded a photo, etc), insert a record in that table (note this is not very efficient and does not scale well if you have many users)
Second, on the browser side, you periodically call a function (with setInterval for example) to query the server for updates and update the widget
The above solution is very simplistic and wont scale.
Hope that helps
You can use the setTimeout() javascript method to trigger a reload of your widget every X milliseconds.
var delay = 5000; // 5 seconds
setTimeout('refresh();', delay );
function refresh(){
doAjaxCall(); // ajax call to get new data and update the widget
setTimeout('refresh();', delay ); // schedule next refresh
}
It might be better to put the reschedule (the last line) inside the ajax callback to start the timer only when the current refresh is finished.
I get the value of $_SESSION[balance] from a MySQL database on every login. How can I update the value in clients browser without reloading the page every 5 minutes? I think it can possibly be done using AJAX?
Sorry if that's too vague I'm absolutely clueless as to where to start on this.
your're right, you need AJAX for this. easiest way is to use $.get(); with the jQuery library
js/jQuery script
window.setInterval(function() {
$.get('script.php', function(balance) {
$('#balance').html(balance); // set the value to the element with the ID balance
});
}, 60000); // execute every minute
in script.php you simply query the database for the balance and echo it
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.
Im currently working on a small search search script build with Jquery and AJAX. Its a live update script that dynamically loads the results in a div.
This is working perfectly but i want to keep track of what answers are being shown. I've tried putting an MYSQL update statement in the results page with a sleep() to prevent updates to the database happening to soon (some questions are shown for .5 seconds, those shouldn't be updated)
Im currently using the follow code:
sleep(5);
$id = $row_rs_results['vragen_id'];
$aantal = $row_rs_results['vraag_getoond'] + 1;
mysql_select_db($database_ruimerleven, $ruimerleven);
mysql_query("UPDATE vragen SET vraag_getoond = $aantal WHERE vragen_id = '$id'");
};
The problem with this is that it slows down the page to a crawl, anyone has a better solution for this? Thanks in advance!
Wouldn't it be better to have a backend process that you send the results to? That way you'd separate the update from the gui front end and it could flush the data to the database at it's leisure. The way your doing it, it would kill performance. Another option is to kick off another process that just does the database update and communicate with it.
I'm not exactly sure what you are going for, but it sounds like you are doing an instant result thing where it brings up results as you type? If that's what you are going for then I would suggest only submitting the AJAX call after the user has stopped typing for a certain amount of time. I would achieve this by putting the AJAX call in a setTimeout, and then every time the user types it resets the timeout.
Example:
var ajax_timeout;
$("#input").keydown(function() {
clearTimeout(ajax_timeout);
ajax_timeout = setTimeout(ajax_call, 500);
});
The php script should be able to update the database every time it gets called.
I have a run.php that has a button on it called "Run". Clicking it does a jQuery $.get() AJAX call back to a response.php on the server, and sends the result to a Javascript callback function getResponse(sData) inside run.php's HTML for display back on the browser. I want to have things such that as response.php runs through a list of tasks, it echoes a response back with the echo command and for getResponse to update a DIV with that status as it moves along. So, let's say I have 5 steps inside response.php, and therefore 5 echo statements back to getResponse().
I tried to get this to work, but what happens is that jQuery waits and then sends one single response all at once, rather than sending as it goes along with the 5 responses.
What's the technique?
The reason I ask is that I have a script that does something to a bunch of files. The first thing it does is a file count, so it updates my progress bar. Then, as it runs through files, it needs to increment my progress bar like every 1000 files.
I think there's no way to make that ajax call to have multiple response in just one call... but what I could suggest is you make a session on php... and in every steps on your tasks function, update that session... then make another ajax call that checks that session if any updates happened... if there is update then do what you have to do....
As you can't really get progress with xmlhttprequest, I suggest you can look into other ways of doing AJAX calls. One of them is through iframe. You can create hidden iframe, set it's sources to request.php and then periodically just check it's content. It should be possible since it's all it the same domain and restrictions does not apply.
iframe might work because it's not that different from normal browser window, meaning that it periodically applies data it gets into DOM even if request hasn't been finished yet. There's potentially might be problems with how different browsers do that, i.e. IE shows new content only if it got more than 4K or something. But it is possible to overcome that, I'm sure.
So, create new hidden iframe, add src attibute to your php script, make that script periodically write something to the client and on the client check what have been written and convert it to shiny GUI stuff.