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...
Related
Current Situation
I've currently got three divs. Let's call them LeftDiv, CenterDiv and RightDiv. LeftDiv and RightDiv both contain an image that randomises every time the page gets "reloaded", ie when you press F5, or visit a different page on my website. This is done using javascript.
Visiting different pages on my site is done with page IDs, like:
Homepage is website.com/index.php
About page is website.com/index.php?page=about
etc
etc
Visiting different pages basically only changes the content on my CenterDiv (which is obviously located in between the LeftDiv and the RightDiv). However, the background images also once again randomise. Which is probably because the page refreshes.
Desired Situation
What I basically want is those images to only randomise (again) when the visitor either refreshes or revisits the website all together (like entering the web-address in the browser again). What this most likely would require I believe is to not have the entire page refresh when a new page ID gets visisted, but rather only refresh the CenterDiv. So now we get to...
The Question
Is there a way to accomplish this? If so, how? What methods are recommended to use?
Thanks in advance for your help.
jQuery makes AJAX calls so much easier. Might want to check it out here
http://api.jquery.com/jQuery.ajax/
For your problem, I think something like this might work:
function changeDivContents(page)
{
$.ajax({
type: "GET",
data: "page="+page,
}
});
}
And then, in the link give an onclick= "changeDivContents('page_you_want_to_load')"
You need to change only content of your CenterDiv. This can be achieved with AJAX calls.
http://en.wikipedia.org/wiki/AJAX
I am currently working on a website that is coded primarily with PHP/MySQL and HTML5 as a means to learn the code and become better. I used to work for a forum that used AJAX to reload the latest posts as if the user had just refreshed the webpage, except it just changed the content dynamically without a full reload.
My webpage: http://vgrnews.com
My specific situation is as follows: The homepage loads the four latest announcements and (soon to be) comments from the MySQL DB and displays them soonest -> latest. It is inside of a div called maincontent.
What I want to do: Have the announcements show up dynamically with AJAX regardless of the user refreshing or not. It would probably poll the server roughly every 5-10 seconds.
I don't plan to keep the homepage refreshing like that, but once I add more content it would be good to know how to refresh a div at regular intervals. I have read up on AJAX, but I don't quite understand all of the logistics, they just give you the code and expect you to pick it up. It is hard to morph the code to be applicable for my website if I don't understand it.
Sorry for the long read and thanks for all the replies!
function reload_content() {
$('#latest_post').load('ajax/get_latest.php');
}
window.setInterval(reload_content, 10000);
I will clarify on Alexander's answer for you. What the load() function is doing is performing an AJAX request to the given URL, and then setting the HTML of the selected div(s) to be the returned content. This means that your server should return proper HTML (and only the HTML you want in that div).
You can see http://api.jquery.com/load/ for more information on load().
If you plan on having your server return an JSON (or XML) representation of the information, you will have to use a jQuery get() (http://api.jquery.com/get/), and then process the returned data with a callback.
Note that both get() and load() are simply implicit applications of the jQuery ajax() method (http://api.jquery.com/jQuery.ajax/)
EDIT:
The setTimeout is just making the browser call the function ever x milliseconds. This is what will have it check every x seconds.
I am new to Jquery. I have a doubt:
For example, in a web page as voting, if you click a button, a counter is incremented by +1. Now, how to draw the url of the button on a website? Therefore, if we provide the url to others, and just click on the URL, the counter should increase by 1 on the website.
Best example of this is FaceBook LIKE.
I prefer to use jQuery, PHP and MySQL
It's a little bit difficult to understand what you're trying to ask but here's my take on it.
Scenario
You have a page at http://mywebsite.com/rating which contains 5 items you can rate on.
Solution
There are two events here that point to the same server side code.
What you need to do is assign an identifier to your button/product/whatever you're trying to rate. So you might have something like this <button ratingname="button1">Rate me!</button>
Now you will have a jQuery function that will use AJAX to communicate with your server and store the increment in the database. This jQuery function will be invoked via an event handler for the button and by going to this url: http://mywebsite.com/rating#button1.
Once your page loads you should check the hash for a value and if one is found then invoke the original jQuery function. You may want to additionally check if the value for the hash is a valid rating button value. (Note you could also use a query string).
I would do it using ajax, and a server side program to record votes.
You could design the page with any look-and-feel. Then add the ajax code to talk to your server-side program and maybe show the user the current votes.
?id=642&point=1
It’s a POST, not a GET, so it could only be done from a form or AJAX, not a simple URL.
//Vote update
$.post(
"http://example.com/folder/vote.php", // url
{ id: 642, point : 1 }, // post-data
function(data){ // response
$("#resultBox").addClass("done"); // show msg
}
);
More reading at http://api.jquery.com/jQuery.ajax/
I need to implement a links-click counter, that will count the number of clicks on the link...
Right now what i am doing is, i am linking the href to redir.php, which will increase the counter in DB and then using header('Location:'); I am redirecting it to the correct URL.
This works but it is certainly not the best approach. In an effort to make my code efficient, how can I make this link counter better? AJAX?
Not much exp with ajax so I wondering how to do in ajax or is there any other better method...
I do not want someone to write a bot script that would make multiple requests to the redir.php and mess up the stats.
You can use
Javascript to make a Ajax call to your "counter.php"
Add a Javascript code (like Google Analytic) on each page to post on the database
Create a "cron job" to analyse the "access_log" (if you count the link in the same domain, server)
Add a PHP code to update the database when each page is generate.
But I think the first javascript method is the best one.
Add a class on the link to spy
Add a "Event handler" to create a AJAX post
Create a simple PHP script to update the database.
Aka
If you links are generated from a source like a CMS instead of by hand, you could pass the link ID to your URL and on the loading of the next page count increment that the link has been clicked. Going this way would require that you reload (without the link ID) the page after that step to make sure that someone copying the link would not make the counter increment needlessly.
This method is bulletproof if your user has javascript enabled, but if your user does have javascript enabled, you could still do the method stated above and through a client side layer, bypass the whole thing and send it through AJAX.
This might seems like redundancy, but this way, you accelerate your process for most of your visitors (without the redirect since you do it through AJAX) and in the case that the javascript doesn't work or is disabled, you have a fail proof system that would avoid missing any click
Building off of #Akarun's answer, here is sample code (in jQuery) for adding a "listener" onto link clicks with "spy" class. Note that I load an image instead of attempting a $.post or other AJAX event -- this is because those won't complete by the time the person navigates away from the page (which clicking on a link is bound to do in most cases), whereas the browser will get off a request for the image in time. It's still a normal PHP script, the browser just thinks it's loading an image.
$(document).ready(function() {
$('a.spy').mousedown(function(event) {
var page_url = "<?=$_SERVER['PHP_SELF']?>";
var target_url = $(this).attr('href');
if(target_url != "#" && target_url != "javascript:void(0);")
new Image().src= "/welcome/track_link/?page_url=" + escape(page_url) + "&target_url=" + escape(target_url);
return true;
});
});
Have you thought of mobile users and other devices?
I believe your first implementation is completely adequate and secure.
You completely control the counting and there is no issue of user manipulation.
It works predictably also.
After all, the ajax will just do the samething in counter.php; Read and update the database. Stay with your present implementation.
Do it the way Google does it:
Waterfront Rentals
A javascript function. The passed code aids security.
Actually looking at the Google source they load an image with the URL as a parameter
window.clk=function(e,b,a,k,i,c,j)
{
if(document.images) {
b=encodeURIComponent||escape;a=new Image;var f=window.google.cri++;window.google.crm[f]=a;a.onerror=a.onload=a.onabort=function() {
delete window.google.crm[f]
};
var d,g,h;if(google.v6) {
d=google.v6.src;g=google.v6.complete||google.v6s?2:1;h=(new Date).getTime()-google.v6t;delete google.v6
}if(c&&c.substring(0,6)!="&sig2=")c="&sig2="+c;a.src=["/url?sa=T&source=",google.sn,"&cd=",b(i),google.j&&google.j.pf?"&sqi=2":"","&ved=",b(j),e?"&url="+b(e.replace(/#.*/,
"")).replace(/\+/g,"%2B"):"","&ei=",google.kEI,d?"&v6u="+b(d)+"&v6s="+g+"&v6t="+h:"",c].join("")
}
return true
};
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/.