how to use "setInterval" with "while loop".? - javascript

I check all documants about setinterval from forum but.. I couldnt find what I want... Here is my question.:
my code is below:
<?php
include('database_connection.php');
$sorgu = $baglanti->query("select * from makale");
while ($sonuc = $sorgu->fetch_assoc()) {
?>
MY TABLE CODE HERE.. ( codes like : <?php echo $sonuc['proje_ismi'] ?> )
<?php } ?>
I call datas to my table from mysql.. But I change database from admin panel..
And What I want is when I change some data from adminpanel... My users will see it immediatly in few sec with setInterval code without refreshing page...
How can I do that in my documants?

The simplest thing you can do is to refresh the page automatically after few seconds:
<script>
// Auto-refresh the page after 5 seconds:
setTimeout(function() {
document.location.reload(true);
}, 5000);
</script>

Related

How to make a button reusable after the first click with AJAX/JQUERY and PHP

I have built a follow/unfollow Twitter like system using PHP. With help of this forum I have been successful creating a dynamic button that allows you to “follow” or “unfollow” each user, using AJAX/JQUERY to run the PHP/MySQL code in the back and avoid refreshing the page when the action happens. The thing is that I am able to run this script on the background only once. Let’s say a user unfollows a member by mistake (my AJAX/JQUERY script won’t have any problem with that), but then wants to follow him again, this is where I am stuck. The page will have to be refresh to make this happen. I know this is happening due to the PHP dynamic data that I am using as you will see in my code.
In the PHP code am running an iteration that output all the members in the database. I am outputting here (for simplicity) just the member’s name and a follow/unfollow button to each one. The php variable $what_class is the result of a PHP function that looks into the database to determine if the user is following or not that member. $what_class will output the strings “follow” of “unfollow” so the class can be defined, and then be targeted by either of the two the Jquery scripts.
PHP CODE
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<button class="<?php echo $what_class; ?>" type="button" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" ><?php echo $what_class; ?></button>
<?php } ?>
Below is the JQUERY scripts, as mentioned before, the button class will be defined by PHP through $what_class. This is the problem when trying to re-use the button after the first time, class won´t change in PHP’s $what_class unless the page is refreshed. I tried to use $(this).removeClass('unfollow').addClass('follow') to change the class using Jquery and have the button to be re-usable but it isn’t working.
JQUERY SCRIPTS TO FOLLOW OF UNFOLLOW
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$.get("follow_actions.php", {unfollow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('follow');
$(this).removeClass('unfollow').addClass('follow');
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("button.follow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$.get("follow_actions.php", {follow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('unfollow');
$(this).removeClass('follow').addClass('unfollow');
});
});
</script>
Does anyone knows how I accomplish having a reusable button without reloading the page? I thank you in advance.
Previous Answer:
What I do for that kind of scenario is to have two buttons. One will be shown to the user, and the other one will be hidden.
<button class="follow" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" >Follow</button>
<button class="unfollow" style="display:none" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" >Unfollow</button>
Just tweak your php code what to show and what not.
When a button is click, hide this button and show the other one.
$(document).ready(function(){
$(".follow").on("click", function(){
$(".follow").hide(200);
$(".unfollow").show(200);
/* PUT YOUR OTHER PROCESSES HERE */
});
$(".unfollow").on("click", function(){
$(".follow").show(200);
$(".unfollow").hide(200);
/* PUT YOUR OTHER PROCESSES HERE */
});
});
Check this JSfiddle.
Update:
We can use toggleClass() of jQuery.
<button class="follow" data-member_id="12" user_id="12">Follow</button>
And the script:
$(document).ready(function(){
$(".follow, .unfollow").on("click", function(){
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$(".follow, .unfollow").toggleClass("follow unfollow");
$(this).text(function(i, text){
return text === "Follow" ? "Following" : "Follow";
});
});
});
Check this JSfiddle.
use <button class="followUnfollow <?php echo $what_class; ?>"
You need to write as less code as possible. Have a common class such as followUnfollow and then check if follow class exists within this element using hasClass function from jQuery.
Have a look at the code below.
<script type="text/javascript">
$(document).ready(function() {
$("button.followUnfollow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
if($(this).hasClass('follow')) { // FOLLOW
$.get("follow_actions.php", {follow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('unfollow');
$(this).removeClass('follow').addClass('unfollow');
} else { // UNFOLLOW
$.get("follow_actions.php", {unfollow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('follow');
$(this).removeClass('unfollow').addClass('follow');
}
});
});
</script>

Redirect after the session finishes in php

Hey guys am really a noob in php...I just want to make a redirect after the session ends..So i have came to know that without js this cant be implemented..So i have modified the code with the help of my friends
<html>
<body>
<?php
session_start();
$_SESSION['logintime'] = time();
echo 'this page needs to be redirected in a minute'
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
$(function(){
var loginTime = <?php echo $_SESSION['logintime']; ?>
var testSession = setInterval(function(){
var currentTime = Date.now() * 1000;
if((currentTime - loginTime) > 60) { //here 60 denotes a minute
<?php session_start();
session_unset();
unset($_SESSION);
session_destroy();
?>
window.location.href = 'www.google.com'; // redirecting process
}
}, 1000);
});
</script>
</body>
</html>
The code runs without errors ..but it isnt redirecting after 60 seconds..
Any guides to make this code work correct would be really appreciated..Thanx
Try this, it goes in the section of your html:
Using html only
<meta http-equiv="refresh" content ="5; url=http://www.target.com/">
5 is the number of seconds. Now you can replace 5 with some PHP generated value.
<meta http-equiv="refresh" content ="<?php echo $limitTime(); ?>; url=http://www.target.com/">
If you want to do it in Javascript use following syntax
setInterval(function () {window.location.href = 'http://www.google.com'}, 60000)
In php you can use header method to redirect url
header("Location: http://www.google.com")

Load JavaScript before Redirecting (CodeIgniter)

This is my code. I already tried, flush(); window_location.. but still it fails. What shall I do? I also tested if the value of $result is being passed and it's fine. The only problem is the JavaScript is not loading. I have other codes with this coding structure but works fine and shows the JavaScript before loading.
function accsettings()
{
$this->load->model('admin_model');
$result = $this->admin_model->accsettings();
if ($result==0)
{
echo '
<script type="text/javascript">
alert("Congratulations! Your profile has been updated.");
</script>
';
$res2 = $this->admin_model->accset_audit();
}
else if ($result==1)
{
echo '<script type="text/javascript"> alert("Error! Current password is not correct."); </script>';
}
else
{
echo '<script type="text/javascript"> alert("New password does not match with the confirmation."); </script>';
}
redirect('/main/accsettings');
}
I would not recommend this way to show 'JavaScript' alert message, if you want to show validation message then please set variable controller and check on view.
In you code you are using headerlocation method to redirect page that is not show up result on browser.
Please use refresh method to show buffer result on browser
redirect('/main/accsettings', 'refresh');
//similar to
header( "refresh:0;url=/main/accsettings" );
You should do the redirect also inside the javascript when you want this to be executed.
Here's how you could achieve this:
<script type="text/javascript">
alert("Error! Current password is not correct.");
setTimeout(function () {
window.location.href = "http://www.google.nl"; //will redirect to google.
}, 2000); //will call the function after 2 secs.
</script>

Reload function that make fancybox appear

i (with the help of user) already did one page that has a function to read a value on a txt file and if it's "1" a fancybox (version 2) with a iframe appear.
Code ReadAndAppear.php
<?php
$lines = file('alerta.txt');
$valrec= $lines[0];
echo $valrec;
if($valrec == 1){
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$.fancybox({
href: "alert.php",
type: "iframe"
});
}); //ready
</script>
<?php
}; // closes if
?>
So, to try that this function/page reload (5-5 seconds) to appear the fancybox if the valrec is "1" I create a new page, lets call it index.php
index.php code
head
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#ReadAndAppear').load('ReadAndAppear.php').fadeIn("slow");
}, 50000); // refresh every 10000 milliseconds
</script>
body
<div id="ReadAndAppear"></div>
unfortunately this code doesn't make the fancybox appear on the index.php when valrec=1. this algorithm only refresh and make appear images, echos etc, but not fancybox.
How can i make refresh and appear on the index.php or even better on ReadAndAppear.php
thanks
You would be better off storing the fancybox function in a separate JS file. Then you could call for it in the callback of the ReadAndAppear load function -
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#ReadAndAppear').load('ReadAndAppear.php').fadeIn("slow", function(){
$.getScript('fancybox.js'); // gets and runs script
});
}, 50000); // refresh every 10000 milliseconds
</script>
In ReadAndAppear.php you can make changes to load the same script -
<?php
$lines = file('alerta.txt');
$valrec= $lines[0];
echo $valrec;
if($valrec == 1){
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$.getScript('fancybox.js');
}); //ready
</script>
<?php
}; // closes if
?>
Now put the script in its own file facybox.js
$.fancybox({
href: "alert.php",
type: "iframe"
});
Honestly doing it this way has both good and bad points though. I think, as I said before in the comments, that I think your logic needs a little rethinking. I shouldn't have to use $.getScript() if my code is organized well and included in the project differently. It would be much easier to maintain.
Moving the script into index.php, I would do something like this :
<script type="text/javascript">
var myRefresh;
jQuery(document).ready(function($){
myRefresh = setInterval(function(){
<?php
$lines = file('alerta.txt');
$valrec= $lines[0];
echo $valrec; // do you need this echo ?
if($valrec == 1){
?>
$.fancybox({
href: "alert.php",
type: "iframe"
});
<?php } else { ?>
clearInterval(myRefresh); // cancel interval if $valrec != 1
<?php
}; // closes if else (php)
?>
},5000); // setInterval
}); //ready
</script>

high CPU usage after JavaScript setInterval

I am having a PHP code which pulls out text from the database, and shows it in a div as links. I am refreshing that DIV every 3000 milliseconds, and the CPU usage is only a few percent higher upon the refresh itself. After 20-25 minutes of constant refreshes, when I click on one of the links, it takes about 20 seconds to open that page, and meanwhile the browser tab freezes up. More refreshes occur - more time it takes to open a link, as well as when more links are opened (if 10-15 links are opened, it gets as slow as 10-12 seconds to open next page). When browser is trying to open the link, 1 processor thread is fully loaded. Here is the code (simplified):
<div id="map1"></div>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<div id="map1">
<?PHP
if (isset($_GET['m'])) {
$selectback = "SELECT parentid FROM MAP_LINK WHERE sysid = " . $_GET['m'];
................
$rowb = ibase_fetch_row($query);
echo "<h6>BACK</h6><h4>
<script>
$('a#back" . $rowb[0] . "').click(function() {
clearInterval(auto_refresh);
$(\"#map1\").load(\"test2.php?m=" . $rowb[0] . "\");
auto_refresh = setInterval(function (){
$(\"#map1\").load(\"test2.php?m=" . $rowb[0] . "\");}, 3000);
});
</script>";
$select = "SELECT sysid FROM MAP_LINK WHERE parentid = " . $_GET['m'];
.........................................
$x = 0;
while ($x < $total_rows) {
$x++;
$row = ibase_fetch_row($query);
echo "<br>Link # " . $row[0] . "
<script>
$('a#" . $row[0] . "').click(function() {
clearInterval(auto_refresh);
$(\"#map1\").load(\"test2.php?m=" . $row[0] . "\");
auto_refresh = setInterval(function (){
$(\"#map1\").load(\"test2.php?m=" . $row[0] . "\");}, 3000);
});
</script>";
}
} else {
echo "<script>
$(document).ready(function(){
$(\"#map1\").load('test2.php?m=56');
auto_refresh = setInterval(function (){
$(\"#map1\").load(\"test2.php?m=56\");}, 3000);
});</script>";
}
?>
This is about the same code I have. The database consists of 4 tables where data is pulled from. The first 6-7 clicks open next page momentarily with no delay, delays start after the 10th click and get bigger with each additional click or refresh.
My question is: How can I make it open immediately or at least faster? There is an error in code. It works, but it's using the CPU a lot and is getting slow enough to not being to navigate on page.
Thank you!
Late for help but you could try chaining setTimeouts together, like this:
function refreshments() {
setTimeout(function(){
//Do stuff
refreshments();
}, 1000);
}
refreshments();

Categories

Resources