Page reloads but doesn't hit server - php

I have the following Ajax logon script. index.php will set a session and then return something like {"status":true,"msgs":[],"url":"\/demo\/administrator\/index.php"}if the username and password checks out. The page then should reload, the PHP script will check if the session is set, and if so, will display the appropriate page.
"Sometimes" with FireFox 21.0 running on Windows 7, the page appears to reload, but then incorrectly re-displays the logon page. When I say "appears to reload", when using FireBug, I see the POST to the server, I then see the console.log "reload page" for a brief amount of time, and then the logon page is displayed. If I then manually reload the page, the session checks out, and the correct page is returned.
To troubleshoot, I put some syslog(LOG_INFO,"got here!"); in my PHP script, and I see it never got accessed a second time, thus my believe the server isn't getting hit after the reload. I've also checked the Apache access log, and I believe it only sees the first POST.
Can anyone let me know what is happening, and how to remedy it? Thank you
$.post('index.php',{task:'logon',username:username,password:password},
function (data)
{
if(data.status==true){
console.log('reload page');
//window.location.href = data.url;
window.location.href = window.location.href;
//window.location.reload();
}
else {msgs.html("<ul>"+mkList(data.msgs)+"</ul>");}
},'json'
);

This answer was really provided by Brian Lacy and user1600124, but they only left comments and didn't post this answer. So, please vote their comments up if you think this is a good answer.
Use window.location.reload(true) to submit data to server
If you don't explicitly tell the browser not to cache pages in the headers.. some browsers will still cache dynamic pages because the parameter that you send is the same.
As an alternate solution, you can append a timestamp to the url that would force browser to get content from server again.

also setting the pragma "no-cache" header for your page could help.
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Avoiding_caching

Related

Force fresh load on browser history back using symfony [duplicate]

I need to somehow detect that the user has pressed a browsers back button and reload the page with refresh (reloading the content and CSS) using jquery.
How to detect such action via jquery?
Because right now some elements are not reloaded if I use the back button in a browser. But if I use links in the website everything is refreshed and showed correctly.
IMPORTANT!
Some people have probably misunderstood what I want. I don't want to refresh the current page. I want to refresh the page that is loaded after I press the back button. here is what I mean in a more detailed way:
user is visiting page1.
while on page1 - he clicks on a link to page2.
he is redirected to the page2
now (Important part!) he clicks on the back button in browser because he wants to go back to page1
he is back on the page1 - and now the page1 is being reloaded and something is alerted like "You are back!"
You can use pageshow event to handle situation when browser navigates to your page through history traversal:
window.addEventListener( "pageshow", function ( event ) {
var historyTraversal = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( historyTraversal ) {
// Handle page restore.
window.location.reload();
}
});
Note that HTTP cache may be involved too. You need to set proper cache related HTTP headers on server to cache only those resources that need to be cached. You can also do forced reload to instuct browser to ignore HTTP cache: window.location.reload( true ). But I don't think that it is best solution.
For more information check:
Working with BFCache article on MDN
WebKit Page Cache II – The unload Event by Brady Eidson
pageshow event reference on MDN
Ajax, back button and DOM updates question
JavaScript - bfcache/pageshow event - event.persisted always set to false? question
Back/Forward Cache
It's been a while since this was posted but I found a more elegant solution if you are not needing to support old browsers.
You can do a check with
performance.navigation.type
Documentation including browser support is here: https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation
So to see if the page was loaded from history using back you can do
if(performance.navigation.type == 2){
location.reload(true);
}
The 2 indicates the page was accessed by navigating into the history. Other possibilities are-
0:The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.
1:The page was accessed by clicking the Reload button or via the Location.reload() method.
255: Any other way
These are detailed here: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation
Note Performance.navigation.type is now deprecated in favour of PerformanceNavigationTiming.type which returns 'navigate' / 'reload' / 'back_forward' / 'prerender': https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/type
Since performance.navigation is now deprecated, you can try this:
var perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
location.reload();
}
jQuery( document ).ready(function( $ ) {
//Use this inside your document ready jQuery
$(window).on('popstate', function() {
location.reload(true);
});
});
This will work 100% when back or forward button has been clicked; also if using ajax.
If it doesn't -- there must be a misconfiguration in a different part of the script.
For example: it might not reload the page if some page (in the previous post) is setting the state to:
window.history.pushState('', null, './');`
so when you do use history.pushState();
make sure you use it properly!
In most cases you will use:
history.pushState(url, '', url);
Not window.history ... and make sure url is defined.
An alternative that solved the problem to me is to disable cache for the page. That make the browser to get the page from the server instead of using a cached version:
Response.AppendHeader("Cache-Control","no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");
Currently this is the most up to date way reload page if the user clicks the back button.
const [entry] = performance.getEntriesByType("navigation");
// Show it in a nice table in the developer console
console.table(entry.toJSON());
if (entry["type"] === "back_forward")
location.reload();
See here for source
You should use a hidden input as a refresh indicator, with a value of "no":
<input type="hidden" id="refresh" value="no">
Now using jQuery, you can check its value:
$(document).ready(function(e) {
var $input = $('#refresh');
$input.val() == 'yes' ? location.reload(true) : $input.val('yes');
});
When you click on the back button, the values in hidden fields retain the same value as when you originally left the page.
So the first time you load the page, the input's value would be "no". When you return to the page, it'll be "yes" and your JavaScript code will trigger a refresh.
I tried all the solutions from the previous answers. No one worked.
Finally I found this solution, which did worked:
(function () {
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload();
}
};
})();
JS Solution That Works On Most Browsers
None of the many other approaches on this page worked for me, perhaps because the "bfcache" is preventing anything from happening when the user navigates back to the page. However, I found that registering a window.onbeforeunload handler works for me in most browsers, and I believe it works because it implicitly invalidates the "bfcache". Here's the code:
window.onbeforeunload = function() {
window.location.reload(true);
}
This event may be triggered in other cases than "back" button navigation, but it my case that doesn't matter. I tested this on the following platforms on recent versions of the listed browsers in August 2021:
Linux: works in Chrome and Firefox.
Android: works in Chrome, Firefox, and Opera.
OS X: works in Chrome and Safari.
iOS: doesn't work in Safari.
In my case I don't really care about mobile. I do care about IE, but don't have access to IE, so I couldn't test it. If someone tries this on IE and can report the result in the comments that would be helpful.
Server Side Response Headers That Fix iOS Safari
I found that iOS Safari also works if I invalidate the browser cache using Cache-Control response header. I.e. sending
Cache-Control: no-store, must-revalidate
fixes iOS Safari. See this SO answer for how to set the Cache-Control response header on various platforms.
Reload is easy. You should use:
location.reload(true);
And detecting back is :
window.history.pushState('', null, './');
$(window).on('popstate', function() {
location.reload(true);
});
I had the same problem, back-button would update the url shown in location field but page-content did not change.
As pointed out by others it is possible to detect whether a change in document.location is caused by back-button or something else, by catching the 'pageshow' -event.
But my problem was that 'pageshow' did not trigger at all when I clicked the back-button. Only thing that happened was the url in location-field changed (like it should) but page-content did not change. Why?
I found the key to understanding what was causing this from: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event .
It says 'pageshow' -event is caused among other things by "Navigating to the page from another page in the same window or tab" or by "Returning to the page using the browser's forward or back buttons"
That made me ask: "Am I returning to the page, really?". "What identifies a page?". If my back-button did something else than "returning to the page" then of course 'showpage' would not trigger at all. So was I really "returning to a page"? OR was I perhaps staying on the same "page" all the time? What is a "page"? How is a page identified? By a URL?
Turns out me clicking the back-button did NOT "change the page" I was on. It just changed the HASH (the # + something) that was part of my url. Seems the browser does not consider it a different page when the only thing that changes in the URL is the hash.
So I modified the code that manipulates my urls upon clicking of my buttons. In addition to changing the hash I also added a query parameter for which I gave the same value as the hash, without the '#'. So my new URLs look like:
/someUrl?id=something#something
Every page that my app considers to be a "different page" now has a different value for its query-string parameter 'id'. As far as the browser is concerned they are different "pages". This solved the problem. 'Pageshow' -event started triggering and back-button working.
This works in Nov 21 in latest Firefox and Chrome.
window.addEventListener( "pageshow", function ( event ) {
var perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
location.reload();
}
});
Use following meta tag in your html header file, This works for me.
<meta http-equiv="Pragma" content="no-cache">
In Chrome 96 perfEntries[0].type is 'reload', when you use the back button
Here is a version that detects for Safari, and if detected executes the older code that is officially deprecated (but is still in Safari).
let isSafari = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 &&
navigator.userAgent &&
navigator.userAgent.indexOf('CriOS') == -1 &&
navigator.userAgent.indexOf('FxiOS') == -1;
if(isSafari) {
window.addEventListener( "pageshow", function ( event ) {
let historyTraversal = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if (historyTraversal) {
// Handle page restore.
window.location.reload();
}
});
} else {
let perfEntries = performance.getEntriesByType("navigation")
if (perfEntries[0].type === "back_forward") {
window.location.reload(true);
}
}
I found the best answer and it is working perfectly for me
just use this simple script in your link
next page
or the button click event
<INPUT TYPE="button" onClick="history.go(0)" VALUE="next page">
when you use this, you refresh your page first and then go to next page,
when you return back it will be having the last refreshed state.
I have used it in a CAS login and gives me what I want.
Hope it helps .......
details found from here

Cookies arent being detected in php or javascript

Im not sure where im going wrong. I have a form that when the contents of the form get processed and sent to the database it also sets a cookie
setcookie("bgremkey",$checkkey, time()+2592000);
then it will redirect the user back to the page they came from. All of this works fine (bar the cookie bit)
then i have it set at the top of every page providing there isnt an session active to check to see if the cookie exists and if it does to redirect but it wont work. im sure that the cookie is there but it wont pick it up
<?php
if(isset($_COOKIE['bgremkey']))
{
header("location:'Check.php?cklog=1");
}
?>
<script type="text/javascript" language="JavaScript">
var acookie = ReadCookie("bgremkey");
if(acookie.length != 0)
{
window.location = " Check.php?cklog=1";
}
this code doesnt generate any errors but it also doesnt do anything. i have tried putting it in the of the page but that didnt work so i then tried the body and that didnt work either
the check page does a bunch of other stuff but thats not the problem since the redirect never happens
i checked the cookies through chrome and the cookie exists and its path is / so the problem is definitely with reading them. it exists but for some reason cant be detected
http://php.net/manual/en/function.setcookie.php
setcookie("cookiename","cookievalue", $time); will only set it for the current path
Whereas: setcookie("cookiename","cookievalue", $time,"/"); will set the cookie for all pages/folders on that domain (note the 4th argument containing the path ).
If you press CTRL+SHIFT+J in google chrome, and click on the Resources tab, you can find the cookies and the path it is valid in. I'd check that out. perhaps this is why?

this.checked creating false positive?

I have a page that has 4 checkboxes that are checked by default. If you uncheck a box, it writes a cookie so that return trips to the page will have saved preferences. The problem I'm having is that the cookies seem to be written no matter what. Going to the page for the first time should create no cookies, but unchecking a box should throw the following code. As it stands, the first time I'm going to my site, the cookies are created.
Where have I gone wrong (I wouldn't be surprised if it is in multiple places).
$('#mycheckbox').change(function() {
if (! this.checked) {
<?php setcookie('key', 'Value', time() + 4800); ?>
}
});
No, this.checked works.
The problem is that the PHP code will always be run, since it's run on the server-side and not interpreted by the browser. All PHP code is executed before the browser even gets the files.
A solution would be to put that PHP in an external file and use jQuery $.ajax to request that file, which would run the code only when desired.
You could also check out the jQuery $.cookie plugin.
As #MarkB already said you are mixing up javascript and php. In this case you should set your cookie with javascript in stead of php. See this post to find out more.
The code as you have it now will always set the cookie, as you already noticed, because the server ignores the javascript code and just runs the php code to set the cookie.

Setcookie won't work?

I set the cookies regularly in a callback page in my Twitter application. Everything works fine.
Now, using jQuery, I submit a form, and the callback function activates a PHP script. That script only needs to set one cookie to the serialized values of $_POST; and the values run fine (both serialized and normal, I echoed them out to debug). The expiration time is set to 1 year ahead. But for some reason, the cookie just won't appear anywhere. Here's the code:
// js/main.js
$('#settings-form').live('submit', function() {
$.post('controllers/settings.php', $(this).serialize(), function(data) { // Everything here works.
if (data == 'OK') // no errors spits out "OK". this works
changeView({'msg': 'Your settings were saved successfully.'}); // This just resets the view and adds a message div at the top. This works
else
changeView({'msg': data}); // This echoes the error if any exists. Doesn't happen, no errors arise
});
return false; // Cancels redirecting after submitting form
});
// controllers/settings.php
setcookie('user_settings', serialize($_POST), strtotime('+1 year'));
I checked all the variables and I even tried setting dummy ones for test (like "boo" instead of serialize($_POST). for some reason that doesn't work.
Any ideas why this is happening? I tried doing a chdir('..'); to make the cookie dir go to the right place, but that doesn't seem to be the problem, checking the cookies inside my browser doesn't seem to work at all, for any path. It just doesn't work at all. I also just tried manually changing the domain and path, but those don't work either.
Firstly, the chdir() thing is a red-herring -- Cookies are domain-specific; the directory path doesn't have any bearing on them.
Cookies can work a bit strangely when you're making ajax type calls, and I think this is what you're seeing -- The server is probably setting the cookie, but the browser may not be setting it in the cookies data it as it's not a page load.
I would suggest you'd be better off using PHP's session handling rather than cookies; it's better for security, less bandwidth (because the whole of the cookie data is transmitted in both directions with every http single request), and more likely to work.
If you really want to use cookies, it may work better if you use Javascript to do it. You can set cookies in your javascript code by accessing document.cookie. (you need to get the syntax right for the cookie string, but JQuery probably has its own functions that makes them easier to work with)

using php and HTTP_REFERER to create a condition for loading js

I'm trying to create a splash page effect on a site I'm working on (I know splash pages are bad etc but I have my reasons), and basically I want to call the script that runs the splash image overlay only if the visitor is coming to the index from an external website. That way if a visitor clicks "home" from an internal page the splash won't launch. I've been searching about and it seems like I can do this with php using $_SERVER['HTTP_REFERER'], but I'm brand new to php and after playing with it all afternoon can't seem to make it work.
The following code loads the script but it doesn't seem to care if the referring URL contains "mysite" and an error message appears at the top of the page reading:
"A PHP Error was encountered
Severity: Notice
Message: Undefined index: HTTP_REFERER
Filename:..."
<?php
$referrer=$_SERVER['HTTP_REFERER'];
if(stristr($referrer, "mysite") == FALSE) {
echo '
<script type="text/javascript">
$(document).ready(function() {
$("#wrapper").hide();
$("#imgContainer").npFullBgImg("/imgs/splash_image.jpg", {fadeInSpeed: 2000, center: true});
$("#logoContainer").fullLogoImg("/imgs/splash_logo.png", {fadeInSpeed: 2000, center: true});
$("#logoContainer").click(function(){
$("#wrapper").show("fast");
$("#splash_kill").remove();
$(this).remove();
});
});
</script>';
}
?>
Any help would be much appreciated. Thanks!
The notice is telling you that a HTTP_REFERER isn't set.
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the
current page. This is set by the user
agent. Not all user agents will set
this, and some provide the ability to
modify HTTP_REFERER as a feature. In
short, it cannot really be trusted.
http://php.net/manual/en/reserved.variables.server.php
A quick search led to this, which provides a little more detail: http://www.electrictoolbox.com/php-http-referer-variable/
Update:
You could try using a session variable. The variable could be a simple boolean, which is set to true if the splash page has been displayed, false otherwise. This would require some session handling on every page that may be an entry point to the website and/or every page where you'd want to display the splash.
http://php.net/manual/en/function.session-start.php
Of course, this would only be viable for the duration of the session.
So, you could use a cookie instead or with this approach.
Personally, I would probably opt for the simple cookie approach, as this is just a splash. No need to add the overhead of sessions for something this simple.
This is what I am trying. I am not sure about the wildcard:
<?php
//echo $ref
$ref = $_SERVER["HTTP_REFERER"];
//if is NOT coming from inside linking
if ( $ref != '*www.example*' )
// send to index and exit
{header("Location:http://www.example.com/index.php");
Exit;
//
}
?>
While you can't completely rely on $_SERVER['HTTP_REFERER'] to be set, I think you will find that it is reliable enough for a splash page. When it isn't set, there is no referer and that will be blank, as it isn't in the header.
You should first test to see if empty($_SERVER['HTTP_REFERER']) and then check to see if it has your own domain in it.
On another note, I was working on an old IIS server that changed the names of some of those $_SERVER variables, and generally messed them up. I'd do a print_r($_SERVER) to see what's up.
if(isset($_SERVER['HTTP_REFERER'])&&!empty($_SERVER['HTTP_REFERER'])) {
$http_referer=$_SERVER['HTTP_REFERER'];
}

Categories