I have a counter that takes a sum from a database column and updates on every page load. I need to convert this to a live counter that updates without page load.
It's on a WordPress site, and I'm hoping not to have to create a separate page outside of WP in order to send the JSON array.
1) Is there any way to use the current page to submit/receive the POST data?
2) What's the best process for converting a simple 'SELECT * FROM' to something dynamic. Is ajax/jQuery the right choice?
Thanks!
Use the following to update the value every 5 seconds
window.setInterval(function(){
$.getJSON('/getLatestCount.php', function(data) {
$('#id_of_element_where_it_needs_to_be_put').html(data.count);
});
}, 5000);
if the query needs to have the contents of a form, use:
window.setInterval(function(){
$.getJSON('/getLatestCount.php', $("#my_form_id").serialize(), function(data) {
$('#id_of_element_where_it_needs_to_be_put').html(data.count);
});
}, 5000);
This doesn't use POST but GET but that shouldn't be a problem i think. In the http file use $_GET['my_field_name'] to access the form values.
You can output the json data in php through echo json_encode()
Looking at your question and that you're asking something for wordpress i'm not sure you know how to do this all though so i won't start going into depts about polling and websocket. This is the easiest way to do it.
Related
I have a question, and I'm hoping one of you will know the answer.
I am running a sql query from php fro a certain bit of information. I am then pulling that info into script and plugging it into an api. I want the api to have access to up to date info every 30 seconds. However, obviously, although the script can run again every 30 seconds ... the php cannot, thus the info is the same.
Is it possible therefore to have the php that runs the sql query refresh once every 30 seconds without refreshing the entire page?
Or ... is there a better way to be doing this. I believe it is no a good idea to be accessing the database from javascript?
Thanks in advance.
You're looking for AJAX. There are plenty of tutorials on the net explaining how to create simple pages powered by AJAX.
A quick example can be found here.
(function() {
setInterval(function() {
$.ajax({
async: true,
dataType: 'json',
type: 'GET',
url: '/echo/json',
success: function(data) {
// You'd use data variable here, but JSFiddle doesn't return anything
$('#test').html(Math.floor(Math.random()*100)-1); // Changes randomly after every fetch
}
});
}, 200);
}());
ajax is wath you are looking for,
ajax allows u to make a call to ur server whitout reloading your page.
i will recomend creating a page that only contains your data, then, on your aplication page load it into a div like
<div id="yourData"></div>
u can use James answer to load it, change '#test' for '#yourData' on any id u have on the div.
if u are using jquery u can use .load() also, for me is more clear, http://api.jquery.com/load/
$('#yourData').load('YourAplication/YourDataGeneratorPage.html');
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 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
I have a PHP page with a mysql connection, a select query and then i'm building a table using PHP. If i wanted to use jQuery AJAX to refresh the data on a setInterval, on the same page, how would i go about doing that? (by the way i can do it to another PHP page but i've never done it if the PHP stuff is on the same page)
If you want to keep making ajax calls i suggest you do long polling, which basically means you have a script that is requesting content via ajax every given time, and it will verify every time if the content has been modified, if not it will wait again and make another call.
I used jQuery Periodical updater for a chat box and it worked perfectly.
If you wnat to learn more about how jQuery and AJAX work, check out this Nettus article
You set the param in request, for instance file.php?ajax=1
The, depending on its value, you render full html or just the necessary elements for ajax
in php:
if($_GET['ajax']) renderAjax();
else renderFullHTML();
in js:
$.get('file.php?ajax=1', function(data) {
$('.result').html(data);
});
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/.