How can I auto update a widget using AJAX? - php

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.

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.

How to fetch records from mysql and check for updates without setinterval or load functions

I have a website which I am working on, just like social web but it is in a simple codes of php, jquery and html.I have made my site updates with jquery load function with interval. User is updated by this load function with interval of 3 seconds. I needed something else which fetch records from mysql and update them again and again because wall posts , likes and unlikes , delete and time ago runs fine but when it comes to comment it is weird because after 3 seconds, the comment which is typed in textarea by the user gets vanished due to this load function. I liked this function but I think it is not accurate for this type of job. So, I need a simple solution of this.
Recently I discover this plugin: https://github.com/paulirish/jquery-idletimer to detect when the users goes idle, perhaps you can update your information based on this.

Update a Div Automatically with Jquery When New Record Added in MySql Database

I'm making a Social networking website for my friends. i wanted to know how i would Update a Div containing few inserted records of the database, when a new record is added in the database. In short you must have seen the live notifications of facebook, which fade in when someone does something . this all happens without the refreshing of the whole live notification div. only the new notification is prepend to the div.
I would like to do this using jquery and AJAX as i have good knowledge about them. and PHP as the server side language.
Thank you in Advance.
P.S : I have searched many websites for the solution, but couldnt find it anywhere. i Even tried going through facebook's Source code but couldnt find it there too ! I hope someone helps me here ! *crossed fingers*
You can either use Ajax Push to send a notification that the post is updated, or you can make it pull-driven. The latter would probably be easier for you if you already know jquery and Ajax with PHP.
Periodically check for new records on an interval (using setInterval, for example) and if you find them, load them to the DOM and fade them in. The interval doesn't have to be very small and waste resources .. maybe something as long as every 30 seconds will do.
setInterval('checkForUpdates', 30000);
var lastTime = (new Date()).getTime();
function checkForUpdates() {
$.get('/php-page-that-checks-for-updates.php?timestamp=' . lastTime
, function (results) {
if (results) { /* fade into dom */ }
}
);
lastTime = (new Date()).getTime();
}
PHP page:
$timestamp = $_REQUEST['timestamp'];
$results = query('SELECT post FROM posts WHERE postTime > "$timestamp"');
echo fetch($results);
As others suggested, you can also mark posts as "read" and use that as an indicator instead of the timestamp, which will also solve a time zone problem with my example. I wouldn't want to add an extra column just to do this, but if you already have one for some other reason it'd be a good idea.
EDIT: This is a pretty old answer, but if you can still do it I would use WebSockets instead of any kind of ajax long polling. I don't think that PHP is a great language (I would suggest using socket.io with Node.js), but it is possible.
Basically it goes something like this:
Create a javascript function on your page that makes an ajax call (with jquery or native xhr or what not) to a php page. The php page keeps track of "new stuff" and returns it when called. The js function, when receiving data, add new tags (divs or whatever) to the notification bar. The function is called every once in a while with javascript's setTimeout function.
If some of these steps are confusing to you please ask a more specific question.
You can use jQuery's $.getJSON() method to access a PHP page. This PHP page would grab all unread notifications (you could add a column in your notifications table called "read" and set it to 0 for unread and 1 for unread) and return them as a JSON feed.
Parse the JSON and make each one a div that shows up on the page. Then wrap this all in a setInterval() and run it every millisecond (or half a second, or quarter of a second, it's up to you).
Also, to mark them as read, set up a click event on these divs that you created from the JSON notification feed. On click, it will contact another PHP page (you can use $.post or $.get) which will receive the id of the notification, for example, and change the read column to 1.

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.

Ajax call with MYSQL Update with a delay in the called page

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.

Categories