Interval refresh a static request - php

I apologize if this seems stupid or redundant, I've search and read related pages with little understanding.
I use this function to call my chat widget to each page. (In case I would like to switch chat server.)
<?PHP include "newchat.php"; ?>
I would like to refresh newchat.php at an interval of 20 minutes. (To prevent chat time out.)
I use this code on newchat.php, which results in the entire main page to refresh. (ie. index.php)
<html>
<head>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
</head>
<body onload="JavaScript:timedRefresh(10000);">
*chat script here*
I think I may need to put script/ajax on each template page, which tells browser to refresh only that element, however I do not understand this code and am not sure if it applies.
Thank you for reading and help you may provide.

Try putting your newchat.php file into a iFrame on your pages instead of directly including it. ie:
<iframe src="newchat.php" id="chatFrame" frameborder="0" width="YOUR-WIDTH" height="YOUR-HEIGHT">
Then you can refresh from with-in the newchat.php file. Or if you want control over it from each page you can use the iframes id to control a refresh from the parent:
document.getElementById('chatFrame').contentDocument.location.reload(true);

Related

How to make a div disappear after PHP execution with ob_flush()

I have a PHP file that I want to show a loading text or an image to the visitor, while it is fully loaded.
As far as I know, I should use ob_flush(); to do so.
I tried the following code:
<?php
ob_start();
echo '<div> Loading </div>';
ob_end_flush();
ob_flush();
flush();
ob_start();
ob_clean();
//my php code
//my php code
?>
With this code everything is ok, the loading text appears first of all and then the PHP exception starts. But my problem is that after the PHP execution completes, the loading text is still on the page and it doesn't disappear.
Please help me solve this problem :)
No, this is not what ob_flush() is for. It is not possible at all with a server side language like PHP. You have to use javascript instead.
Here is the roughly simplified and not 100% accurate description what happens when you request a PHP webpage:
Browser sends a request to the server "Hey server, give me page Home"
Server runs the PHP script for page Home
Usually, the PHP script will generate some output. The server will collect this output.
When the script has completed, the server says "OK Browser, here is your Home page", sends the output (the response) to the browser and then closes the connection.
The connection is now closed and the server has already forgotten that the browser has even asked for a page 1 second ago.
The browser will happily display the newly receieved webpage. There is no way to make something happen in the browser now for your PHP script.
That's called the Request Response Pattern and it's still somewhat fundamental to the web.
So how can you get your loading overlay now? When you can accept that the loading overlay doesn't work on the initial page request, but everytime a user klicks a link on your site, you can use following simple approach.
<!DOCTYPE html>
<html>
<head>
<title>Loading overlay test</title>
</head>
<body>
Click me!
<script>
document.addEventListener(
'click',
function() {
if(event.target.matches('a')) {
document.body.innerHTML = "Loading next page ...";
}
},
false
);
</script>
</body>
</html>
If your page loads fast you will probably not see the effect. I kept the example as simple as possible with some plain text instead of a real loading overlay, you can use this as a starting point.
When you absolutely need an overlay for the first page request, things get more complicated. Here is a non-production ready and ajax-less example:
<?php
// Detect 1st page hit
if(empty($_GET['fetch_real_page'])) {
// Loading page - keep as simple(fast) as possible,
// prevent any slow database queries etc.
?>
<!DOCTYPE html>
<html>
<head>
<title>The loading page</title>
</head>
<body>
Loading first page...
<script>
// This will instantly request the "real" page
window.location.replace(window.location.href + '?fetch_real_page=1');
</script>
</body>
</html>
<?php
exit;
// (Does not need to be called explicitely
// when nothing comes after the if-else construct)
} else {
sleep(2);
// Simulates a slow page load,
// do all the heavy database stuff that slows down your page here.
// Then, output the "real" page:
?>
<!DOCTYPE html>
<html>
<head>
<title>The real page</title>
</head>
<body>
Click me!
<script>
// Set up the loading overlay for secondary requests
document.addEventListener(
'click',
function() {
if(event.target.matches('a')) {
document.body.innerHTML = "Loading next page ...";
}
},
false
);
</script>
</body>
</html>
<?php
}
?>
Things to consider:
You need to extend every internal link with fetch_real_page=1
Sooner or later you need to deal with additional $_GET parameters, so you must extend this code, or switch to cookies or the session to check whether the request is a secondary one or not.
The end of the road will be a javascript/ajax-driven single page app but I think this is beyond the scope of your question.
Beware of this unreadable mix of PHP tags and HTML, code like that is frowned upon for good reasons. This is for demonstration only.

Return Redirect with body in Laravel

I'm trying to do a redirect with body in Laravel. I've tried this:
return Redirect::to($log_in_url)->with('body','<html><head><title>Redirecting to your page</title></head><body>If you are not redirected within 5 seconds, please cl ick here.</body></html>');
I look in the network tab, I don't really see anything.
The question is that how would one make a delayed redirection by showing an HTML waiting page before the actual redirection happens?
You're making a handful of false assumptions:
The with method puts the thing into the session so that you can access it after the redirection. A common usecase is to set messages and then redirect the user.
Don't expect magic by just setting the thing body.
There's no such a standardized redirection called "redirect with body" as you stated. If you need such a thing, you have to implement it.
I assume you're having one of those vBulletin-like redirect styles in mind. To implement it in Laravel context, you gonna need a mediatory view to do a clientside redirect for you after a set amount of delay. Let's name it redirect.blade.php:
<!doctype html>
<html lang="en">
<head>
<title>Redirecting...</title>
<script>
window.setTimeout(function () {
window.location = "{{ $url }}";
}, 5000);
</script>
</head>
<body>
If you are not redirected within 5 seconds,
please click here.
</body>
</html>
With this in place, your controller will pass a $url to this mediatory view and let it be rendered to do the clientside redirection:
# Controller method
return view('redirect', ['url' => $log_in_url])
This style of redirection won't be working if JavaScript is disabled and that's why they put a link into the page content and warn the user about it.
Some take a hybrid approach:
<noscript>
<meta http-equiv="refresh" content="5;url={{ $url }}" />
</noscript>
The reason that they don't go with the refresh header/meta tag in the first place is that it's not specified in the HTTP standard. Read more.
I strongly suggest that you look into alternatives. This is so 1990 and not user-friendly at all.
As a visitor, if I deal with a website that makes me wait for 5 godddamn seconds, I'd just leave. That's why people used to make browser extensions to workaround the vBulletin's login screen waiting time!
Embrace simplicity and just do a regular HTTP redirect. It's best for all humanity.
It's not a task for Laravel. You can just return page with meta, or using javascript.
// Controller
return view('redirect');
// View redirect.blade (Regular html page with additional meta tag)
<meta http-equiv="refresh" content="5;url=http://www.google.com/" />

Javascript behaving inconsistently with PHP include files

I have a very simple javascript animation that looks like this
$(function() {
$('#slider1').cycle();
$('#slider2').cycle();
});
Im then calling in this script like this into my head:
<script type="text/javascript" src="js/slider.js"></script>
Then the divs that have the id "slider1" and "slider2" are contained in php include files being called into the page like this:
<?php include('assets/col1.php'); ?>
The code in the include file looks like this:
<div id="slider1">
<img src="images/image1.png" />
<img src="images/imgae2.png" />
<img src="images/image3.png" />
<img src="images/image4.png" />
</div>
Which works fine except when you get to IE8 or IE9. The javascript will work about 75% of the time which is why this has me baffled. When you load the page or come back to the page, every once in awhile it just doesn't activate the javascript and all the images render in one long column (essentially what it looks like with no js function)
I suspect its something in the order in which IE9 is loading the PHP and the javascript but I am only a novice in both js and php so some very clear help on how to fix this would be really great. Thanks in advance.
Soooo long story long...
PHP will return interpreted HTML. Every time you include a file, PHP will flush the buffers, which means, certain content is returned to the browser prior to others. While this happens, the page is still in a loading state.
For this reason, you need to make sure you call $(document).ready(function(e){ ... });. This will give you code a chance to finish flushing the buffers and load into the browser, before the javascript is executed..
I had encountered a similar issue while using Dojo, which I solved as follows:
Set the main or the parent div display style as none:
<div id="g_body" style="display:none">
Now once Dojo finishes loading, I change the display style to block using the dojo.ready function:
require(["dojo/ready", "dojo/parser", "dijit/registry"], function(ready, parser, registry){
ready(function(){
if(document.getElementById("g_body")!= null){
document.getElementById("g_body").setAttribute("style","display:block");
}
});
});
The pages then only shows when Dojo elements are completely loaded.
I believe there is something similar in jQuery, but I am not sure. Probably:
$(document).ready(function() {});
Hope this helps.

HTTP Referrer on Redirection

I have a small script that redirects users to main site if they come from a banner on my/other remote sites.
<?
.
..
...
....
header("location:$golink");
?>
But google analytics will not show the referrer site (where the script is working) instead it shows the url where the banner is clicked. Obviously I can not keep a track of all sites where banner appears and dont want to. I want the refferer to be the site where the script is working. How do I have to use the $_SERVER['HTTP_REFERER']; in order to do this ?
GA has a method that will let you to override the default referring URL (document.referrer) with a specified value.
So if you want to keep the redirect server-side, you can append the referring URL as a query string param in your header() call, and then look for it on the target page and specify it as the referring URL.
I don't know how you are building your $golink variable, but basically you would add something along the lines of:
$golink .= "?ref=" . $_SERVER['HTTP_REFERER'];
Use a & instead of ? if there are already URL params, and the code above assumes using ref as the URL param, so use whatever var you want.
Then on your target pages, before your _trackPageview call, you would add
_gaq.push(['_setReferrerOverride', ref]);
ref would be a javascript variable with the value of the ref=xxx query string param. For some weird reason Javascript does not have a native way to grab URL param values, nor does GA provide an (exposed) solution. If you already have a solution on your pages for grabbing URL params (like something from a framework or a function you've already made) then use that. Otherwise it's pretty easy to find a javascript function that will do it for you.
There are a couple benefits to doing it this way:
You don't have to worry about the visitor seeing an interstitial page.
You don't have to worry about GA not getting a chance to fully load before redirect
You can see the referrers tied directly to your landing pages, because with the interstitial page, you will always see that interstitial page as the referrer, and will have to look at referring url reports for the interstitial page.
Yes, G.A is blind to this kind of server-side stuff. And their PHP Api is not helpful either.
However, you could have a short redirection page, holding the GA tag inside like this :
<html>
<head>
<title>A web page that points a browser to a different page after 2 seconds</title>
<meta http-equiv="refresh" content="2; URL=<?php echo $golink; ?>">
<meta name="keywords" content="automatic redirection">
<script>var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'))</script>
</head>
<body>
If your browser doesn't automatically go there within a few seconds,
you may want to go to
the destination
manually.
</body>
</html>
Notice the $golink variable in the meta tag.
If you use this, do not forget to replace UA-XXXXX-X by your real account number.
Credits : optimized GA tag goes to Mathias Bynens
[EDIT : javascript only version]
<html>
<head>
<title>Redirecting you...</title>
<script>var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'))</script>
<script>
<!--
if (window.addEventListener)
window.addEventListener('load', function() { window.location="<?php echo $golink; ?>"; }, false);
else
window.attachEvent('onload', function() { window.location="<?php echo $golink; ?>"; });
// -->
</script>
</head>
<body>
</body>
</html>

Php Location("some other page")

I'm new to PHP and this is something that I don't know how to do, even though I have been searching it.
I know that redirecting can be made with Location("some page"). I also read that this works just if there is nothing displayed to user.
What I want to do is:
Display a message to user. echo "message.redirecting...."
Wait for 2 seconds sleep(2);
Then redirect Location("some page");
Any ideas?
Andrew
This is part of an assignment and javascript is not allowed. Only PHP.
You can use a meta refresh, which is just a html meta tag placed inside the <head> of your page. Like this:
<meta http-equiv="refresh" content="2;url=http://newurl.com/">
This will redirect the page to the http://newurl.com after 2 seconds.
Do not do it this way.
It's VERY bad usability.
And there is not much sense in saying "redirecting".
That's legacy of ancient ages of raw HTML sites. No good site using such redirects these days.
Redirect with no messages.
Unfortunately you can't do that. header() calls, such as header('Location: '); rely on http headers, which have to be sent before any output is sent to the client.
I reccomend using a Javascript Redirect if you want a message displayed to the users.
<html>
<head>
<script type="text/javascript">
<!--
function delayer(){
window.location = "../javascriptredirect.php"
}
//-->
</script>
</head>
<body onLoad="setTimeout('delayer()', 5000)">
<h2>Prepare to be redirected!</h2>
<p>This page is a time delay redirect, please update your bookmarks to our new
location!</p>
</body>
</html>
or you can do a php redirect like this:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
?>

Categories