I want to refresh a PHP page every few second with SetInterval(); and it stop refreshing the page if a data added to database. so, when it refreshing my PHP page, it always checking is there a new data added to the database or not..
I'm trying to use this kind of logic but its not working...
$query = mysql_num_rows(SELECT id_example FROM table_example);
$a = count($query);
$b = $a+1;
IF($a==$b)
{
Stop_refreshing_the_page;
}
else
{
Refresh_with_setInterval();
}
is there anyone can suggest me better logic/algorithm/code example to do that??
Which part is not working?
Also, setInterval is probably not what you want if you are refreshing the entire page each time -- seems like a simple setTimeout and reload would do the trick, then simply not print that when you have db results.
Edited for OP
I assume this is not valid PHP, but you should get the idea.
$previous_count = $_GET['previous_count'];
$query = mysql_num_rows(SELECT id_example FROM table_example);
$result_count = count($query);
if ($previous_count == $result_count)
{
// this should render some javascript on the page including $result_count
}
The resulting javascript would be something like:
<script type='text/javascript'>
window.setTimeout( function(){
window.location = window.location.pathname + "?previous_count=<?php echo $previous_count; ?>";
}, 2000);
</script>
Related
I've got a basic like button concept on my site that visits url.tld?action=love and adds +1 to the link's database column.
It's a hassle redirecting to another page all the time though. Is it possible to click the button, and send a request to the URL without actually redirecting to a new URL? Also maybe refresh the button afterwards only so that the count updates?
For a general idea of what my download button is this is in the header:
<?php require_once('phpcount.php'); ?>
<p class="hidden"><?php
$time = time();
for($i = 0; $i < 1; $i++)
{
PHPCount::AddHit("$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", "127.0.0.1");
}
echo (time() - $time);
/*echo "PAGE1 NON: " . PHPCount::GetHits("page1") . "\nPAGE1 UNIQUE: " . PHPCount::GetHits("page1", true);
echo "\n\n" . PHPCount::GetHits("page2");
$ntot = PHPCount::GetTotalHits();
$utot = PHPcount::GetTotalHits(true);
echo "###$ntot!!!!$utot";*/?></p>
And this is an example of my "love" button.
Love <span class="count">'. PHPCount::GetHits("$package_get?action=love", true).'</span>
The reason I used this method is because people create pages, and I wanted the like button to work out of the box. When their page is first visited it adds their url to the database, and begins tallying unique hits.
This is basically adding a new link column called downloadlink?action=love, and tallying unique clicks.
use the following code. assgin id="btn_my_love" to that button and add this code to you page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//assign url to a variable
var my_url = <?php echo "https://alt.epicmc.us/download.php?link='.strip_tags($package_get).'?action=love"; ?>;
$(function(){
$("#btn_my_love").click(function(){
$.ajax({
url:my_url,
type:'GET',
success:function(data){
//comment the following result after testing
alert("Page visited");
},
error: function (request, status, error) {
alert(request.responseText);
}
});
//prevent button default action that is redirecting
return false;
});
});
</script>
Yes, it is possible. I am assuming you know what ajax is and how to use it, if not I am not going to give you the code because some simple reading on ajax as suggested by #Black0ut will show you how. But the basic steps are as follows:
Send ajax request to a PHP script that will update +1 vote to the database
In the PHP script, add +1 to the database and return some data to the ajax, maybe the new number of votes
Parse the return data in your JavaScript and update the button accordingly
I have a translation plugin that utilizes Google's free website translation tool. I don't use their API, but only provide some creative options in how the tool is used on the website.
How it works: User clicks on flag or drop-down that fires event, then adds ?lang variable to the end of url after translation. User is able to change the url directly by modifying the ?lang url variable in the address bar.
This is tricky, especially because right now I'm using client-side functionality to do the work. I am using location.href to refresh the page, which also adds back the lang variable to the url after navigating to new page.
My problem is when user clicks on link to new page, this is what happens:
User clicks on new page link
Page refreshes to the new url WITHOUT the lang variable.
jQuery kicks in and refreshes page a 2nd time to add the url variable.
New page is now shown to user with the requested url variable.
This is 2 refreshes! Obviously not efficient.
I'm seeing that it might be best to change this to server side refresh instead, using PHP. I need some guidance on how jQuery and PHP will interact, if someone could show me an simple example.
Here is the jQuery code I have now for a single language case, when user changes url directly in the browser.
<script type="text/javascript">
jQuery(document).ready(function($) {
$.cookie("language_name", "Afrikaans");
$.cookie("flag_url", "<?php echo home_url(); ?>/wp-content/plugins/google-language-translator-premium/images/flags24/Afrikaans.png");
var language_name = $.cookie("language_name");
var lang = GetURLParameter('lang');
var googtrans = $.cookie("googtrans");
var lang_prefix = $('a.af').attr("class").split(" ")[2];
if (lang == null && language_name == 'Afrikaans') {location.href = document.location.href.split("?")[0] + "?lang=" + lang_prefix;}
function GetURLParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
if (googtrans != '/en/af') {
doGoogleLanguageTranslator('en|af');
}
});
</script>
<?php
if (empty($_GET['lang'])) {
header('Location: $_SERVER['REQUEST_URI'].'?'.$_SERVER['QUERY_STRING'].'&lang=en');
die;
}
?>
This could have a bit more logic to it, but it is the basic idea. This code would have to be as close to the top of the page as possible, because headers are only allowed to be sent before any output is printed on the page.
You can use JavaScript to append the lang parameter to every link on page load. You'll need logic to ignore external links and add ?lang or &lang based on the preexistence of a query string. And of course, it wouldn't do anything unless lang was already specified in the current URL.
You could modify your existing code to something like this:
...
if (lang) {
jQuery("a").each(function () {
// Logic here
});
}
else if (language_name == 'Afrikaans') {
location.href = document.location.href.split("?")[0] + "?lang=" + lang_prefix;
}
...
Take a look at Jquery : Append querystring to all links for examples of how to append the query string parameter.
I have an index.php file that I would like to run getdata.php every 5 seconds.
getdata.php returns multiple variables that need to be displayed in various places in index.php.
I've been trying to use the jQuery .load() function with no luck.
It's refreshing the 12 <div> elements in various places on the index.php, but it's not re-running the getdata.php file that should get the newest data.
But If I hit the browser refresh button, the data is refreshed.
getdata.php returns about 15 variables.
Here is some sample code:
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php'); // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow");
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Here's an example of GetData.php:
$query = "SELECT column1, COUNT(column2) AS variable FROM table GROUP BY column";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 '];
$variable = $row['variable '];
if($column1 == "Text1") { $variable1 = $variable; }
elseif($column1 == "Text2") { $variable2 = $variable; }
... continues to variable 15 ...
}
Then further down the page the HTML elements display the data:
<div id="Hidden_Data"></div>
<div id="Show_Data_001"><?php echo $variable1; ?></div>
<div id="Show_Data_002"><?php echo $variable2; ?></div>
<div id="Show_Data_003"><?php echo $variable3; ?></div>
...
I tried using the data parameter as suggested here:
https://stackoverflow.com/a/8480059/498596
But I couldn't fully understand how to load all the variables every 5 seconds and call them on the index page.
Today the GetData.php page just returns $variable1 = X; $variable2 = Y and so on.
UPDATE
For some reason the jQuery is not loading the GatData.php file and refreshing the variables.
I tried adding to "Hidden_Data" to the include('GetData.php') and then the variables are readable on the page.
If I remove this part, the page displays "variable not set" warning that suggesting that the jQuery is not loading the GetData.php script into the Hidden_Data <div>.
Try
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php', function() { // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow"); });
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Above is assuming, that your code returns snippet of HTML elements (Show_Data_XXX), but now that you've clarified your question above wont help you alone...
What you need to do is either in your php send back new value elements or send back your results as data and update existing elements.
Put your elements into a php Array and then send it back
data.php after sql call
$results = Array();
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 ']; // change Text1 in db to Show_Data_001 in html or vice versa
$variable = $row['variable '];
$results[$column1] = $variable;
}
echo json_encode($results);
in your javascript something like this...
$.getJSON('GetData.php',function(data) {
$.each(data, function(key, val) {
$('#'+key).text(val);
});
});
I didn't put the fadeOut and fadeIn into the example, because it complicates it a bit. You could do fadeOut to all those elements before calling getJSON and the fadeIn as the results pouring in. Hope this helps
First of all, make sure you have correct respond from server, just like this:
//We won't use load() to load content for now
window.setInterval(function(){
$.ajax({
url : "path_to_your_php_script.php",
type : "GET",
beforeSend: function(){
//here you can display, smth like "Please wait" in some div
},
error : function(msg){
//You would know if an error occurs
alert(msg);
},
success : function(respondFromPHP){
//Are you getting distinct results every 5 sec?
alert(respondFromPHP);
return;
//if respondFromPHP contains data you want
//ONLY THEN, add some effects
}
});
}, 5000);
The only difference between this approach and yours, is that, you can handle errors and make sure you are getting data you want.
Can you show me the code of GetData.php?
Rather than using Jquery.load you can actually get the page with $.post or $.get and format your results from GetData.php to Json or xml you can easily map it to your javascript.
Using $.post it will allow you to have a callback after getting the value from GetData.php and you can check it if it's working right or not. If it gets a data from your GetData.php then you can populate it to your DIV elements.
You can check more information regarding POST and GET here:
http://api.jquery.com/jQuery.post/
I recently came upon a site that has done exactly what I want as far as pagination goes. I have the same basic setup as the site I just found.
I would like to have prev and next links to navigate through my portfolio. Each project would be in a separate file (1.php, 2.php, 3.php, etc.) For example, if I am on the 1.php page and I click "next project" it will take me to 2.php.
The site I am referencing to accomplishes this with javascript. I don't think it's jQuery:
function nextPg(step) {
var str = window.location.href;
if(pNum = str.match(/(\d+)\.php/i)){
pNum = pNum[1] * 1 + step+'';
if ((pNum<1) || (pNum > 20)) { pNum = 1; }
pNum = "".substr(0, 4-pNum.length)+pNum;
window.location = str.replace(/\d+\.php/i, pNum+'.php');
}
}
And then the HTML:
Next Project
I can't really decipher the code above, but I assume the script detects what page you are on and the injects a number into the next page link that is one higher than the current page.
I suppose I could copy this code but it seems like it's not the best solution. Is there a way to do this with php(for people with javascript turned off)? And if not, can this script be converted for use with jQuery?
Also, if it can be done with php, can it be done without dirty URLs?
For example, http://www.example.com/index.php?next=31
I would like to retain link-ability.
I have searched on stackoverflow on this topic. There are many questions about pagination within a page, but none about navigating to another page that I could find.
From your question you know how many pages there are going to be. From this I mean that the content for the pages themselves are hardcoded, and not dynamically loaded from a database.
If this is the approach you're going to take you can take the same course in your javascript: set an array up with the filenames that you will be requesting, and then attach event handlers to your prev/next buttons to cycle through the array. You will also need to keep track of the 'current' page, and check that incrementing/decrementing the current page will not take you out of the bounds of your page array.
My solution below does the loading of the next page via AJAX, and does not change the actual location of the browser. This seems like a better approach to me, but your situation may be different. If so, you can just replace the related AJAX calls with window.location = pages[curPage] statements.
jQuery: (untested)
$(function() {
var pages = [
'1.php',
'2.php',
'3.php'
];
var curPage = 0;
$('.next').bind('click', function() {
curPage++;
if(curPage > pages.length)
curPage = 0;
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
$('.prev').bind('click', function() {
curPage--;
if(curPage < 0)
curPage = (pages.length -1);
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
});
HTML:
<div id = "pageContentContainer">
This is the default content to display upon page load.
</div>
<a class = "prev">Previous</a>
<a class = "next">Next</a>
To migrate this solution to one that does not have the pages themselves hardcoded but instead loaded from an external database, you could simply write a PHP script that outputs a JSON encoded array of the pages, and then call that script via AJAX and parse the JSON to replace the pages array above.
var pages = [];
$.ajax({
url: '/ajax/pages.php',
success: function(json) {
pages = JSON.parse(json);
}
});
You can do this without ever effecting the structure of the URL.
Create a function too control the page flow, with an ajax call
function changePage(page){
$.ajax({
type: 'POST',
url: 'myPaginationFile.php',
data: 'page='+page,
success: function(data){
//work with the returned data.
}
});
}
This function MUST be created as a Global function.
Now we call the function on page load so we always land at the first page initially.
changePage('1');
Then we need to create a Pagination File to handle our requests, and output what we need.
<?php
//include whatever you need here. We'll use MySQL for this example
$page = $_REQUEST['page'];
if($page){
$q = $("SELECT * FROM my_table");
$cur_page = $page; // what page are we on
$per_page = 15; //how many results do we want to show per page?
$results = mysql_query($q) or die("MySQL Error:" .mysql_error()); //query
$num_rows = mysql_num_rows($result); // how many rows are returned
$prev_page = $page-1 // previous page is this page, minus 1 page.
$next_page = $page+1 //next page is this page, plus 1 page.
$page_start = (($per_page * $page)-$per_page); //where does our page index start
if($num_rows<=$per_page){
$num_pages = 1;
//we checked to see if the rows we received were less than 15.
//if true, then we only have 1 page.
}else if(($num_rows % $per_page)==0){
$num_pages = ($num_rows/$per_page);
}else{
$num_pages = ($num_rows/$per_page)+1;
$num_pages = (int)$num_pages;
}
$q. = "order by myColumn ASC LIMIT $page_start, $per_page";
//add our pagination, order by our column, sort it by ascending
$result = mysql_query($q) or die ("MySQL Error: ".mysql_error());
while($row = mysql_fetch_array($result){
echo $row[0].','.$row[1].','.$row[2];
if($prev_page){
echo ' Previous ';
for(i=1;$i<=$num_pages;$i++){
if($1 != $page){
echo "<a href=\"JavaScript:changePage('".$i."');\";> ".$i."</a>";
}else{
echo '<a class="current_page"><b>'.$i.'</a>';
}
}
if($page != $num_pages){
echo "<a class='next_link' href='#' id='next-".$next_page."'> Next </a>';
}
}
}
}
I choose to explicitly define the next and previous functions; so here we go with jQuery!
$(".prev_link").live('click', function(e){
e.preventDefault();//not modifying URL's here.
var page = $(this).attr("id");
var page = page.replace(/prev-/g, '');
changePage(page);
});
$(".next_link").live('click', function(e){
e.preventDefault(); // not modifying URL's here
var page = $(this).attr("id");
var page = page.replace(/next-/g, '');
changePage(page);
});
Then finally, we go back to our changePage function that we built initially and we set a target for our data to go to, preferably a DIV already existing within the DOM.
...
success: function(data){
$("#paginationDiv").html(data);
}
I hope this gives you at least some insight into how I'd perform pagination with ajax and php without modifying the URL bar.
Good luck!
I'm creating a online training 'powerpoint' like series of pages. It will be pretty straight forward and have the pages set out as such:
page1.php
page2.php
page3.php
...
page20.php
I'll be going old school and use an iframe to hide the address bar as people shouldn't be able to catch onto the naming convention and skip ahead. (Its not too serious, so I want to keep it simple).
What I want to do is based on the current page that they are on, say for example page5.php create links to page4.php and page6.html. Obviously without having to code each page manually.
It would be ideal if ths were a javascript function as I dont want the address to show up in the browsers info bar but I'm open to php tricks as well.
Any ideas how to do this?
Use window.location. You can put it in a function like so:
<script type='javascript'>
function goto(url) { window.location=url; }
</script>
<a href='#' onclick='goto("page3.php"); return false;'>Previous</a>
<a href='#' onclick='goto("page5.php"); return false;'>Next</a>
You could also go so far as to use a session variable to hide it, that way you could just do something like this (I hope my PHP skills are still good):
<?php
// At Beginning of first script
start_session();
$MAX_PAGE = 20; // Set this to the highest page number
if(!isset($_SESSION['curpage'])) {
$_SESSION['curpage'] = 1;
} else {
// __EDIT: Added page max and mins.
if($_GET['go'] == 'prev' && $_SESSION['curpage'] > 1) {
$_SESSION['curpage']--;
} else if($_GET['go'] == 'next' && $_SESSION['curpage'] < $MAX_PAGE) {
$_SESSION['curpage']++;
}
}
?>
And then put this in the page where you need it.
<?php
include("page$_SESSION[curpage].php");
if($_SESSION['curpage'] > 1) {
echo "<a href='page.php?go=prev' rel='prev'>Previous</a>";
}
if($_SESSION['curpage'] < $MAX_PAGE) {
echo "<a href='page.php?go=next' rel='next'>Next</a>";
}
?>
Note that Web Crawlers won't be able to do much with this though, when it returns a different page each time.
A little expansion on Pikrass's function, to deal with first/last scenarios:
function goto(url) { window.location=url; }
var curPage = parseInt(location.href.replace(/page([0-9]+)\.php/, ''))
if (curPage <= 1) {
// First page, no 'back' link
document.write('Back');
} else {
var backPage = curPage-1;
document.write("Back");
}
if (curPage >= 9) { // Replace with highest page number
// Last page, no 'next' link
document.write('Next');
} else {
var nextPage = curPage+1;
document.write("Back");
}
URLs are not hidden if you view the source of the page, but they don't show up in the browser's status bar when hovering over the link, as requested.
Edit Updating RegEx with Pikrass' more specific one, to deal with other digits elsewhere in the URL. Thanks Pikrass!
var actuPage = parseInt(location.href.replace(/[^0-9]/, ''))+1;
location.href = 'page'+actuPage+'.php';
That should work if you have no other number in your URLs. If you do, you'll have to change the pattern for replace.
The code is for the next page, change the +1 to -1 for the previous one.
Here is MidnightLightning's version with a better RegExp to get the current page, which works even if you have other numbers in your URLs.
function goto(url) { window.location=url; }
var regPage = /page([0-9]+)\.php/;
var match = regPage.exec(location.href);
var curPage = parseInt(match[1]);
if (curPage <= 1) {
// First page, no 'back' link
document.write('Back');
} else {
var backPage = curPage-1;
document.write("Back");
}
if (curPage >= 9) { // Replace with highest page number
// Last page, no 'next' link
document.write('Next');
} else {
var nextPage = curPage+1;
document.write("Back");
}
I love when an answer is built by several guys. :)
If you can, prefer a PHP code, as suggested. It's much more "clean".
Sounds like you want to use query string variables, so page.php?page=1, page.php?page=2, page.php?page=3 and so on
Why dont you use ajax instead of an iframe?
Well, doesnt matter, you tagged the question jquery so i think you can find usefull using another link attribute to 'tell' js where to redirect.
I mean:
$.(document).ready(funciton(){
//i use the live method becose.. you know, maybe in the future
//you will go with ajax ;)
//live method is avbaiable in jquery 1.3!
$("a.navigation").live('click', function(){
window.location = $(this).attr("rel");
});
});
This let your html markup free from many onclick functions in the <a> tags.
So, your markup will then look something like:
Go to page 1
Go to page 2
<!-- .. and so on.. -->
Or, if you still wanna hide real urls, you can do:
Go to page 1
Go to page 2
<!-- .. and so on.. -->
with this js (maybe not embedded into the page source?)
$.(document).ready(funciton(){
$("a.navigation").live('click', function(){
window.location = 'page' + $(this).attr("rel") + '.php';
});
});
But you'll never be able to completely hide the page urls, if youre planning to use js links.
You could hide them using php, and an hashed strings twin, but i dont know if it worth the game.
Other suggested a regexp way to calculate the pages number and pages links; I will go printing the links via PHP: will let you control the global behavior much better (we dont know how many pages you have, and if theyre numbers is database-related, even the information you gave us would make me think that you have all the page[x].php fisically on your server)