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.
Related
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.
I have a webpage that run a query on a db and reports the results. Currently the page auto refreshes itself every 10 seconds in order to display (almost) real-time data.
This is probably a very inefficient way of accomplishing this but as of right now I'm not really sure what alternatives there are.
What options do I have to present real-time data on a php webpage?
you can use node.js and socket.io. This is great example to get you started:
http://book.mixu.net/ch13.html
or you can use ejabberd and strophe js library.
I used both of that solution for real time stuff and I found node.js and socket.io much easier to implement.
Depending on what your data is for and how you are using it, ive recently started putting data display functions into seperate pages and then using jquery to load those pages into dives on my main page at page load and then reloading the divs on a timer and on a reload function if the refresh is needed sooner, that way your whole page does not refresh making it flash and go blank but instead the data just gets nicely updated.
var paused = false,
auto_refresh = setInterval(
function()
{
if (paused) return false;
$('#mot').fadeOut('slow').load('motview.php?view1=$dayd&viewdate=1').fadeIn('slow');
$('#work').fadeOut('slow').load('workview.php?view1=$dayd&viewdate=1').fadeIn('slow');
$('#motday').fadeOut('slow').load('motdaylist.php? view1=$dayd&viewdate=1').fadeIn('slow');
$('#notelist').fadeOut('slow').load('notelist.php?dayd=$dayd').fadeIn('slow');
}, 60000);
$(document).ready(function(){
$('#mot').load('motview.php?view1=$dayd&viewdate=1');
$('#work').load('workview.php?view1=$dayd&viewdate=1');
$('#motday').load('motdaylist.php?view1=$dayd&viewdate=1');
$('#notelist').load('notelist.php?dayd=$dayd');
});
function reloaddivs()
{
$('#mot').load('motview.php?view1=$dayd&viewdate=1');
$('#work').load('workview.php?view1=$dayd&viewdate=1');
$('#motday').load('motdaylist.php?view1=$dayd&viewdate=1');
$('#notelist').load('notelist.php?dayd=$dayd');
};
the above im using to display 4 lots of data on one page that all updates nicely on a timer or after ive interacted with a page by calling reloaddivs
Inspect your page carefully to identify exactly what is the data which is to be updated every 10 seconds - chances are it will not be the whole page (menus, navigation, headers, footers).
Cache all that data say, every 10 minutes, or every hour - especially if data driving any of those elements are being dragged from databases.
Then include the panel containing the dynamic data.
Better yet might be to load the dynamic data using Ajax to refresh every n seconds.
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.
ok folks,
I have created a PHP page that is querying a database, and through a whileloop, displays the contents of that database table with a REMOVE and PUSH button. The REMOVE button removes it from the database entirely, and the PUSH button pushes that entry into another database and sets a variable that the entry has been pushed.
What I'm running into is that I can't quite get the page to refresh, in turn running an new query of the first database and displaying only those entries that have not been removed or pushed.
I can only get the query to run correctly if I manually refresh the page, whether it be F5 or control+r (command+r).
What is the proper way to refresh the page so that the query will run again on page load?
If you want to reload the page using Javascript, try this:
window.location.reload(true);
You can also see this answer:
How to reload a page using JavaScript?
there are two ways
If putting extra load on db is not a problem, use jquery methods likes $.get()
$.get('url',{},function(data){
//load results in appropriate div;
});
If you don't want to put any extra load on database just hide the row when it is removed or pushed.
$('.remove').click(function{
$(this).css('display','none');
});
similarly make it for pushed
Do you have some extreme caching setup on your web hosting solution?
If maintaining nice-looking URLs on this page is a non-issue you could always set a timestamp in PHP and append it to the string.
I'm not big on PHP but a javascript example would look something like this.
ts = new Date();
urltorefresh += '?timestamp=' + ts.getTime();
location.href = urltorefresh;
This would make sure the page is absolutely not in the browser cache since this specific URL have never been requested before.
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.