jquery update page when db update - php

I've a page that show data inserted in a mysql db; I'd like (if it is possible) that this view page automatically update when a record is added to the db (data are not inserted from the same page or may be inserted from another user).
thanks in advance
ciao h.

First way (easiest but annoying):
Add a meta refresh to the page and the full page refreshes every x amount of time.
Second way (AJAX):
I'm assuming this is what you want.
Load default HTML page etc... lets call it index.php
On above page create a <div> element with style display:none like this
<div id="mydata" style="display: none;"></div>
Create a PHP page that retrieves and formats the database data and prints it out in x format, i.e a table or p tags. no headers or page specific stuff just data and simple tags
On index.php put something like this
<script type="text/javascript">
function update() {
$.ajax({
url: 'http://www.example.com/getData.php?q=latest',
success: function(response) {
$('#mydata'.html(response);
}
});
}
// .ready function
$(function() {
// do setup stuff here, I think there is a refresh timer or something
// that you'd use to trigger it every x amount of time
// i.e something like this
update();
});
</script>
EDIT: AJAX HTTP streaming forces data out to users

I know sure on the best method to do this, but and quick-and-easy solution would be to get the total number of rows in your table on page load. Then every x seconds use an AJAX script to re-check that table's row count. If it has changed you could have extra logic that then fetches the new rows.

I was thinking about this last night and realized that node.js (http://nodejs.org/) might be perfect for this if you're looking for an event driven system. There is a good tutorial on getting started using node.js at http://net.tutsplus.com/tutorials/javascript-ajax/learning-serverside-javascript-with-node-js/.

Related

Fullcalendar auto refresh if db changes

I'm developing app using Fullcalendar v1.
I successfully integrate connection to mysql database so my events are loaded from db as json array. But my app are going to use more than 2 people in one moment so i need automatically refresh after my db changes. If one user remove event, calendar refresh for all other users which see this calendar.
I have one experimenting script which i made. It works but not as well as i want.
I know, this script is completely bad but i was frustrated.
<script>
var i = setInterval(function(){
last_id = $.cookie('last_id');
$.get("foo.php", function(data) {
var id = data;
if(last_id !== id) {
$('#calendar').fullCalendar('changeView', 'month');
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('refetchEvents');
$('#calendar').fullCalendar( 'rerenderEvents');
last_id = $.cookie('last_id', data);
}
});
},500);
</script>
It works pretty simple ... foo.php loads number of rows. If this number is other than last number saved in cookies, calendar will be refreshed.
This method has tons of disadvantages and mistakes. It works only for deleting and creating events. Not for moving etc. And it is slowing app by getting results every 500ms ..
Have you better solution for this ?
I have the similar structure.. get data from DB as JSON...
I make a modal for change a event...
When i press the button who calls my db to update the event..
I use behind... a function on jQuery called ( .trigger('click') ) so..
$('.fc-prev-button').trigger('click');
$('.fc-next-button').trigger('click');
//Hide Modal.. button have a data-dismiss="modal"
$('#closeEdit').trigger('click');
That's my solutions because when load fullCalendar this call events.. param who get data from my db... so when you change the month this is called again for reload the data and don't load the full month with data..
Sorry for my english and i hope to help you, Happy Coding !!

refreshing table with jquery/Ajax -breaks links to database/javascript

I am amending some results tables that display rows from a mysql database to refresh automatically. I am new to this so have based it on
Refresh a table with jQuery/Ajax every 5 seconds
This works fine and I have tested it by asking for making the request to the server display the time so i can see the change when the refresh occurs.
My problem is that if i apply this to a table dislaying returned sql results (also using the jquery tablesorter). Both my sql and jquery fail unless I move all the files and code they are dependant upon to the php page i echo the table on. This is now making my pages a mess. So what is the best way to refresh and manage a results table with ajax and where should dependant files/code be located?
cheers
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('getTable.php');
setInterval(refreshTable, 5000);
}
</script>

Javascript getting count from db continuosly

Hi there Everybody!
I am facing a little issue.
I have a DIV where I need to show the count of rows from the database.
The problem is that when the page refresh the count is not still updated because the database mySQL takes a while, so I have to refresh the page again.
Do you know how can I show the count of the rows maybe with javascript? In a way that the count of the rows will be continuosly checked and updated without page reloading..
If I need jQuery for this, just to let you know I am on version 1.3.2
Let me know!
Thanks so much!
yea sure, ajax it... first, it does sound odd that when u refresh the page the database isnt ready, but lets assume there is a sync issue where db gets updated out of sync with the current page... the solution is ajax
function doCountUpdate(){
$.get("url_to_return_count",function(data){
assuming the returned data is a number
$("#myDiv").text(data);
setTimeout(doCountUpdate, 1000);
}
}
I think at page load, You can do that by simply a ajax call to a function and return the row and display it on a DIV.
$(document).ready(function() {
// put all your jQuery goodness in here.
$.ajax({
url: "somepage.php",
success: function(data){
$('#div_id').text(data);
}
});
});

Auto refresh when new user comes online

I have a table in the database which includes all active users. I then have a user list which needs refreshing to see who is the latest users online.
Whats the best way to tackle this?
The user list is always just who is in the active_users table.
Thanks for reading.
AJAX
You could use an AJAX request to pull regularly the list of active users and display them on your website.
You may want to cache that list for a little while on your server in case you have a lot of users requesting it constantly.
Or, if the list is long, or if you decide to pull a lot of HTML markup with the list, you could also regularly poll your server to check whether there are updates to the (cached...) list since the last time the client updated the list. The reply will be a simple true or false, and the client will only have to request the new list when it has changed.
Meta refresh tag
You could also use the meta refresh tag, either to update the entire page, or an iframe if you don't mind iframes.
Refresh after one minute:
<meta http-equiv="refresh" content="60" />
Or with an url:
<meta http-equiv="refresh" content="60;url=http://site.com/list.php?counter=1" />
Manual update
Finally, you may just add a button or a simply a link at the end of the list, and the user could decide for herself whether to reload or not.
Other considerations
As JoeGeeky pointed out in the comments, for performance and bandwidth reasons, you may want to implement a counter which limits the maximum number of times the user list is loaded. This is valid for Ajax and Meta refresh tags. In javascript you could simply have a variable incrementing every time you load the list, and in case of the meta refresh tag you could add the counter in the url as a get variable.
Also those three approaches do not exclude each other but should be combined: Use Ajax for the folks with javascript activated, a meta refresh iframe in a noscript tag as a fallback for the ones with javascript disabled (as mentioned by stagas), and a button or link for manual update once the maximum list reload count has been reached.
If your userlist is short, for example, you are just displaying the latest five users, I would go with a simple polling with Ajax to a PHP script that returns that data.
You can adjust the polling to whatever your needs are,
$(document).ready(function () {
function refreshUserlist () {
$.ajax({
url: "user_list.php",
success: function (data) {
// code to refresh your website with the info out of data
setTimeout(refreshUserlist, 5000);
}
});
}
refreshUserlist();
});
Simplest way I can think of is that you can make a simple php page that lists the data, and use jQuery .load() function to load that php's html response into a div
$("#divid").load("active-users.php");
Make a php script to retrieve the list of active_users and return a <ul> list. Then use jQuery and setInterval() to fetch that list with $.ajax() and replace the list every 1-2 minutes or so with $('#active_user_list').html(new_list_data). Here's what it might look like (untested) :
setInterval(function() {
$.ajax({ url: 'script_to_fetch_active_users_list.php', success: function(new_list_data) {
$('#active_user_list').html(new_list_data);
} });
}, 1000*120);
The php script is up to you...

Refresh Using Ajax/PHP

Further to my question yesterday (here), I am working on a webpage that has a section that shows 'live' order details.
The top half of my webpage has Spry Tabbed Panels. One of the panels contains an include call to a separate php page that I have created (getOpenOrders.php). This contains an SQL query to obtain all open orders and then puts the details into a table.
As a result, the table of open orders is shown in the Spry panel. What steps do I now need to take to have this refresh every 15 seconds?
Do you really want to call the database every 15 seconds for each user? isn't that an overload?
I'm not saying that your database will be overloaded, but, thats how you shouldn't do things!
Edited
you should show an image, or the link to that page in order to gt an appropriate answer, because it all depends in what are you doing in the table.
because I don't know, I will give you an answer on what probably is happening.
Because you said that you're new to the ajax world, let's make things simple, and not to complicate on the you should return a JSON object and use it to re populate your table. :)
So we will start with 2 buttons (Previous and Next) so the user can move the data that is showing (you probably don't want to give him/her 100 lines to see right?)
let's say that you have 2 pages, a showData.php and getTable.php, in the showData.php you will need to load jQuery (wonderful for this) and add a little code, but where the table is to be placed, just add a div tag with an id="myTable" because we will get the data from the getTable.php file.
getTable.php file has to output only the table html code with all the data in, without no html, body, etc... the idea is to add inside the div called myTable all the code generated by getTable.php
Let's imagine that getTable.php gets a page variable in the queryString, that will tell what page you should show (to use LIMIT in your MySQL or PostgreSQL database)
You can use jQuery plugin called datatables witch is one of my choices, check his example and how small code you need to write! just using jQuery and Datatables plugin.
The first description follows the jQuery.Load() to load the getTable.php and add as a child of the div and wold do this for the previous and next buttons, passing a querystring with the page that the user requested. It's to simple and you can see the website for that, if you prefer to use the DataTables plugin, then just follow their examples :)
if you, after all this need help, drop me a line.
<META HTTP-EQUIV=Refresh CONTENT="15; URL=<?php print $PHP_SELF ?>">
This should be in between the head tags.
-or-
header('Refresh: 15');
This should be before the head tag and directly after the html tag.
As said by balexandre, a different method should be used. One that does not require a database hit every 15 seconds for every single user that is connected to the site. But, there is your answer anyways.
Although, balexandre makes a very good point, if you do decide that you need a refresh, you could simply do something like this in your JavaScript:
window.onload = function( )
{
setTimeout( 'window.location.refresh( )', 1500 );
}
(I've not tested the above code, so syntax may need to be tweaked a little, but you get the idea)

Categories