PHP echo text then sleep 10 seconds then echo another text - php

I've tried solutions from below links. But none of them give luck.
php-output-text-before-sleep
php-output-data-before-and-after-sleep
php-time-delay-using-ob-flush-with-loading-message
Actually below is my script.
<?php
include 'ini/INI.class.php';
$CompIP = $_SERVER['REMOTE_ADDR'];
$inidata = (parse_ini_file("guard.ini",true));
$atm = time()-$inidata["guard"][$CompIP];
if ($atm>60) { $atm = 1; }
echo "<p>You will be redirected to report page in <span id='counter'>" . $atm . "</span> second(s).</p>";
sleep($atm);
//my
//100
//line
//user report from mysql
$ini = new INI('guard.ini');
$ini->data['guard'][$CompIP] = time();
$ini->write();
?>
Still I get the whole content include 'You will be redirected to .......' after $atm (pause seconds) seconds.
My Workaround
<?php
include 'ini/INI.class.php';
$CompIP = $_SERVER['REMOTE_ADDR'];
$inidata = (parse_ini_file("guard.ini",true));
$atm = (time()-(isset($inidata["guard"][$CompIP]) ? $inidata["guard"][$CompIP] : 0));
if ($atm<60)
{
echo "<p>You will be redirected to report page in <span id='counter'>" . (60-$atm) . "</span> second(s).</p> <script type='text/javascript'> function countdown() { var j = document.getElementById('counter'); j.innerHTML = parseInt(j.innerHTML)-1; if (parseInt(j.innerHTML)<=0) { j.innerHTML = 0; location.href = 'tr.php'; } } for (i=1;i<=" . (60-$atm) . ";i++) { setTimeout(function(){ countdown(); },i*1000); } </script>";
} else { mysqlreport; $ini = new INI('guard.ini');
$ini->data['guard'][$CompIP] = time();
$ini->write();
}
?>

You can use JavaScript for this purpose and pass variables from PHP to JavaScript simply by writing the JavaScript code inside "echo". I think something like this will do the trick.
For redirection, the below example will give you an idea:
<?php
$url = "http://google.com";
$step = "1000";
$start = 12;
echo 'Redirection After <h1 id="counter">'.$start.'</h1> ';
echo '
<script>
var x = '.$start.';
setInterval(function(){
if(x==1){
window.location = "'.$url.'";
}
document.getElementById("counter").innerHTML = x;
x--;
}, "'.$step.'");
</script>';
?>
As for your content that you want to output, just place a tag and with JavaScript. Also, you can update it every 10 seconds; the technique is this, how you do it is up to you.

Related

Protect Email with PHP - output is two words

This is my coding:
<?php
function protected_email($phpemail,$text='',$echo=true)
{
$pieces = explode("#", $phpemail);
$return = '
<script type="text/javascript">
var a = "<a href=\'mailto:";
var b = "' . $pieces[0] . '";
var c = "' . $pieces[1] .'";
var d = "\' class=\'email\'>";
var e = "</a>";';
if($text != ''){
$return .= 'document.write(a+b+"#"+c+d+\''.$text.'\'+e);';
}else{
$return .= 'document.write(a+b+"#"+c+d+b+"#"+c+e);';
}
$return .= '
</script>
<noscript>Please enable JavaScript to view emails</noscript>';
if($echo == true)
{
echo $return;
}else{
return $return;
}
}
?>
<?php echo protected_email('change#email.com', Their Title); ?>
I want to display the person's title instead of their email address, but I cannot get both words to show in their title, unless I remove the space between. How do I get it to dsiplay both words?
Display this:
Their Title
Rather display than:
change#email.com
I'm sure it is something really simple, but I am at a mental block right now.

Can't get .trigger('click'); working

I'm working on date-based trigger in php, and want to auto click a button with this code:
<?php
$oldDate = metadata('item', array('Dublin Core', 'Date'));
$latestDate = explode("/", $oldDate);
$year = $latestDate[2];
$month = $latestDate[1];
$day = $latestDate[0];
$newDate = $month.'/'.$day.'/'.$year;
$newestDate = new DateTime($newDate);
echo $newestDate->format('jS M Y');
$t = time();
$nt = strtotime($newDate);
if($nt <= $t){
} else {
echo "<script> $(document).ready(function(){
$('#gatemodal').trigger('click');
});</script>";
}
?>
but the trigger click event doesn't fire up. Don't have a clue where the fault is. I've tried changing the trigger line into this:
$('#gatemodal')[0].click();
and
jQuery(document).ready(function(){
jQuery('#gatemodal').trigger('click');
still not working.
On the echo part, set a variable and assign it (e.g. $fail='1'), then on your php file check whether $fail has been set and it is equal to one then have your script.
`<?php if (isset($fail)&& $fail=='1'){ ?>
<script type="text/javascript">
jQuery(document).ready(function(){
$('#gatemodal').trigger('click');
});
</script>";
`

How to retain current current pagination page number when webpage is refreshed?

I have simple pagination included in my homepage in order to display the latest news/images from my server. The pagination is working fine but when i try to move to other page number example page 2, the page loads but after refreshing it goes back again to page 1. I am new to PHP , Ajax and Jquery so I can't figure out where to solve this problem. Here are my codes:
pagination.php
<?php
function paginate($reload, $page, $tpages, $adjacents) {
$prevlabel = "‹ Prev";
$nextlabel = "Next ›";
$out = '<div class="pagin page_style">';
// previous label
if($page==1) {
$out.= "<span>$prevlabel</span>";
} else if($page==2) {
$out.= "<a href='javascript:void(0);' onclick='load(1)'>$prevlabel</a>";
}else {
$out.= "<a href='javascript:void(0);' onclick='load(".($page-1).")'>$prevlabel</a>";
}
// first label
if($page>($adjacents+1)) {
$out.= "<a href='javascript:void(0);' onclick='load(1)'>1</a>";
}
// interval
if($page>($adjacents+2)) {
$out.= "...\n";
}
// pages
$pmin = ($page>$adjacents) ? ($page-$adjacents) : 1;
$pmax = ($page<($tpages-$adjacents)) ? ($page+$adjacents) : $tpages;
for($i=$pmin; $i<=$pmax; $i++) {
if($i==$page) {
$out.= "<span class='current'>$i</span>";
}else if($i==1) {
$out.= "<a href='javascript:void(0);' onclick='load(1)'>$i</a>";
}else {
$out.= "<a href='javascript:void(0);' onclick='load(".$i.")'>$i</a>";
}
}
// interval
if($page<($tpages-$adjacents-1)) {
$out.= "...\n";
}
// last
if($page<($tpages-$adjacents)) {
$out.= "<a href='javascript:void(0);' onclick='load($tpages)'>$tpages</a>";
}
// next
if($page<$tpages) {
$out.= "<a href='javascript:void(0);' onclick='load(".($page+1).")'>$nextlabel</a>";
}else {
$out.= "<span>$nextlabel</span>";
}
$out.= "</div>";
return $out;
}
?>
/////////////////////////////////////////
Home.php
<?php session_start(); ?>
<?php
$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action == 'ajax'){
/* Connect To Database*/
$dbname = 'banaue.com';
$link = mysql_connect("localhost","root","") or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $link) or die("Couldn't select database");
include 'pagination.php'; //include pagination file
//pagination variables
$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
$per_page = 1; //how many records you want to show
$adjacents = 5; //gap between pages after number of adjacents
$offset = ($page - 1) * $per_page;
//Count the total number of row in your table*/
$count_query = mysql_query("SELECT COUNT(title) AS numrows FROM news");
$row = mysql_fetch_array($count_query);
$numrows = $row['numrows'];
$total_pages = ceil($numrows/$per_page);
$reload = 'Home.php';
//main query to fetch the data
$result = mysql_query("SELECT * FROM news ORDER BY date_posted LIMIT $offset,$per_page");
//loop through fetched data
while($test = mysql_fetch_array($result)){
$id = $test['title'];
echo "<div class='content' stye=margin-bottom: 20px;>";
echo'<div class="img_content" ><img src='.$test['img_path'].' style=height:520px;width:100%;></div>';
echo"<p class=para_news2 style=margin-left:10px;><font color='#336699'>" .$test['title']."</p></font><br /><br />";
echo"<p class=para_news4 style=margin-left:10px;width:100%;><img src='images/user.gif'>&nbspStory By: <font color='lavander'>" .$test['author']."</font></p>";
echo"<p class=para_news4 style=margin-left:10px;width:100%;><img src='images/calendar.gif'>&nbspDate Posted: <font color='red'>". $test['date_posted']. "</font></p>";
echo"<p class=para_news3 style=margin-left:10px;width:100%;><img src='images/comments.gif'>&nbsp<font color='black'>". $test['intro']. "</font></p><br>";
echo"<a href ='news.php?title=$id'><font style='float:right;margin-right:10px;background:url(images/bg_header.jpg);padding:2px;'>Read more ...</a><br>";
echo "</div>";
}
echo paginate($reload, $page, $total_pages, $adjacents);
} else{
?>
<!DOCTYPE html>
<head><!-- Head declaration -->
<script type="text/javascript">
$(document).ready(function(){
load(1);
});
function load(page){
$("#loader").fadeIn('slow');
$.ajax({
url:'Home.php?action=ajax&page='+page,
success:function(data){
$(".outer_div").html(data).fadeIn('slow');
$("#loader").fadeOut('slow');
}
})
}
</script>
</head>
<body>
<!-- Body Content -->
<div class="main_body" style="height:auto;">
<!-- Top Stories Query-->
<div class="outer_div">
</div>
</div>
</body>
</html>
<?php }?>
Please help me with this problem so that i can move on....
You could use a cookie to store the current pagination position in the clients web browser and read it back when creating the page, to start pagination from last position.
Something like this
setcookie('pagination_pos',$pagination_pos,time() + 86400); // 86400 = expire after 1 day
and then read it back
echo 'Current position '($_COOKIE['pagination_pos']!='' ? $_COOKIE['pagination_pos'] : 0);
this will read the current position from the cookie, if no cookie is there it falls back to 0.
Okay as you requested on how to use it in your code, I made a simple example function you can use in your code:
function getPaginationPos(){
if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
setcookie('pagination_pos',$_REQUEST['page'],time() + 86400);
return $_REQUEST['page'];
} else {
return ($_COOKIE['pagination_pos']!='' ? $_COOKIE['pagination_pos'] : 1);
}
}
this will check if there is a "page" variable in the request and if so it will store the position as a cookie. If no "page" variable is in the request it will check if there is a cookie or return 1.
If I understand your code right you have to replace this line
$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
with
$page = getPaginationPos();
I see another problem in the javascript "load" function where you force page 1 on reload
$(document).ready(function(){
load(1);
});
you can try this:
$(document).ready(function(){
load();
});
add also a check for the page variable to the javascript function, to handle the case if page is not set.
<script type="text/javascript">
$( document ).ready(function() {
load()
});
function load(page){
if (typeof page === 'undefined') {
page = ''
} else{
page = '&page='+page
}
$("#loader").fadeIn('slow');
$.ajax({
url:'Home.php?action=ajax'+page,
success:function(data){
$(".outer_div").html(data).fadeIn('slow');
$("#loader").fadeOut('slow');
}
})
}
</script>
based on Sir Manuel's code, if you don't want to store your variable to be stored in cookies you can try to put it in session variable.
change this line:
function getPaginationPos(){
if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
setcookie('pagination_pos',$_REQUEST['page'],time() + 86400);
return $_REQUEST['page'];
} else {
return ($_COOKIE['pagination_pos']!='' ? $_COOKIE['pagination_pos'] : 1);
}
}
into this:
function getPaginationPos(){
if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
$_SESSION['pages'] = $_REQUEST['page'];
return $_REQUEST['page'];
} else {
return $_SESSION['pages'];
}
}
and this:
$(document).ready(function(){
load();
});
into this:
$(document).ready(function(){
load(<?php print $_SESSION['pages']; ?>);
});

PHP Search: Using Jquery to alter a php a value

I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});

javascript for onClick not executing?

ok maybe i must put all my code:
<?php
include('header_application.php');
$obj_clean->check_user();
$limit = 10;
if(!isset($_GET['page']))
$page = 1;
else
$page = $_GET['page'];
$from = (($page * $limit) - $limit);
$msg = "";
if (isset($_GET['unblock']))
{
$code = $obj_clean->unblockUser($_GET['unblock'],$_GET['code']);
if ($code == "error")
{
$msg = "Could not delete message!";
}
else
{
$msg = "You have unblocked ".$code;
}
}
//Get dynamic data required for this page from the database
$users = $obj_clean->getContacts($_SESSION['user_id'], $from, $limit);
$rows = $obj_clean->getContactsCount($_SESSION['user_id']);
include ("header.php");
?>
<div class="innerContainer">
<head>
<script type="text/JavaScript">
function yesnolist(val)
{
var e = confirm('Do you want to send a free chat request?');
if (e == true)
{
window.location.href = "http://www-rainbowcode-mobi/confirmfreechat.php";
//window.location('http://www-rainbowcode-mobi/confirmfreechat.php');
return true;
}
else
return false;
}
</script>
</head>
<span class="headings2">CONTACTS</span>
<?php if (isset($msg) && !empty($msg)) echo "<br/><font color='red'>".$msg."</font>"; ?>
<br/><br/>
<?php
if (count($users) > 0)
{
echo "<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
foreach ($users as $user)
{
//Breaks the unique code into 3 parts so that the numeric part can be a different colour
$codeLength = strlen($user['unique_code']);
$firstPartLength = $codeLength - 5;
$uniqueCode3 = substr($user['unique_code'], -2);
$uniqueCode2 = substr($user['unique_code'], -5, 3);
$uniqueCode1 = substr($user['unique_code'], 0, $firstPartLength);
echo '<tr>';
echo '<td>';
echo '<a class="charcoal_link" style="line-height: 20px;" href="'.ADDRESS.'view_profile.php?id='.$user['profile_id_contact'].'">'.$uniqueCode1.'<span class="pink_text">'.$uniqueCode2.'</span>'.$uniqueCode3.'</a>';
$requestor_id = $_SESSION['user_id'];
$profile_id = $user['profile_id_contact'];
$rel1 = $obj_clean->hasRelation($requestor_id,$profile_id);
$rel2 = $obj_clean->hasRelation($profile_id,$requestor_id);
if($rel1 && $rel2)
{
echo " ";
//echo 'Free Chat';
echo 'Free Chat';
}
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "You have no contacts yet";
}
?>
</div>
<?php include("footer.php"); ?>
hope this will help better
Free Chat
should be:
Free Chat
try this:
function yesnolist()
{
if (confirm('Do you want to send a free chat request?'))
window.location = "http://www-rainbowcode-mobi/confirmfreechat.php";
}
.
.
.
<a href="#" onClick="yesnolist()">
I'd assume changing the URLs to valid domains might help things, so try:
window.location.href = "http://www.rainbowcode.mobi/confirmfreechat.php";
window.location('http://www.rainbowcode.mobi/confirmfreechat.php');
function yesnolist()
{
var e = confirm('Do you want to send a free chat request?');
if (e == true)
{
window.location = "http://www-rainbowcode-mobi/confirmfreechat.php";
return true;
}
else
return false;
}
and
<label onClick="return yesnolist();">Free Chat</a>
You can not pass onclick event on (a href="") tag because href part redirects the page and after that the javascript redirect part is called.
Or
(a href="#" onclick="return yesnolist();")Free Chat(/a)

Categories