PHP header(Location:'index.php') and javascript not being executed - javascript

My problem is, when the user logout. The login page is being called and the index page is showing but the url is saying
https://mysite/logout.php
instead of
https://mysite/index.php
which means my javascript files included in the index.php ain't being loaded, so you cant log in again without refreshing the page manually.
Link in home.php the page you reach after login
<p class="mc-top-margin-1-5">Logout</p>
I have the following logout page (logout.php)
<?php
session_start();
require_once 'php/class/class.user.php';
$user = new USER();
if(!$user->is_logged_in())
{
$user->redirect('index.php');
exit;
}
if($user->is_logged_in()!="")
{
$user->logout();
$user->redirect('index.php');
exit;
}
?>
my user functions as follow (class.user.php)
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
}
what am I missing?

Your function is_logged_in() returns a boolean, TRUE, but you are checking the return value with:
if($user->is_logged_in()!="")
That is, checking if it's an empty string.
Also, and more importantly, is_logged_in() doesn't return anything if the user is not logged in. That function should be something like:
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
else { return false; }
}
And the check should be something like:
if(!$user->is_logged_in())

so i ended up with a not very nice solution:
I changed the link in home.php
`<p class="mc-top-margin-1-5">Logout</p> `
To a button
<button id="btn-logout">Logout</button>
and added its functionality in a jquery function
$(function(){
$("#btn-logout").bind('click', function () {
window.location.href = "http://example.com/logout.php";
})
});
my logout.php ended up looking like
<?php
session_start();
unset($_SESSION['user_session']);
session_destroy();
?>
<html>
<head>
<script>
window.location.href = "https://example.com/index.php";
</script>
</head>
<body>
</body>
</html>
So going from refresh page in php using header. I ended up with js and jquery. Its not a nice solution above, but it works!

Related

Automatically update with AJAX

I'm currently using this code on my webpage:
<?php
$url = "https://www.toontownrewritten.com/api/invasions";
$data = json_decode(file_get_contents($url));
if (!empty($data->invasions)) {
echo "<h1 style='text-align:center;margin:auto;padding:2px;font-size:16px;font-weight:bold;text-decoration:underline;padding:2px;'>Invasion Tracker</h1>";
$i = 0;
foreach($data->invasions as $title => $inv) {
print "<h3 style='text-align:center;margin:auto;'><b>District:</b> {$title}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Cog:</b> {$inv->type}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Progress:</b> {$inv->progress}
</h3>";
if (count(($data->invasions) > 1)) {
if (end($data->invasions) !== $inv) {
print "<hr>";
} else {
print "<br style='font-size:2px;'>";
}
}
}
} else {
echo "<h1 style='text-align:center;margin:auto;padding:2px;color:darkred;font-weight:bold;'>No invasions!</span>";
}
?>
I'm looking to make it refresh every 10 seconds via AJAX. However, I keep reading you need to make a function, but I'm not sure how I'd do that with the API? Every 10 seconds, that API is being updated, which is why I'd like this to be updated with AJAX every 10 seconds. Currently, I have it so the user has to manually refresh. Any help is appreciated!
You can simply reload the page with the method proposed here
But if you wanna have an AJAX implementation which just refereshes a part of your html nice and tidy, You gonna have to
Almost forget your PHP code
use the following code to implement the request to the url
$.ajax({
url: "https://www.toontownrewritten.com/api/invasions",
})
.done(function( data ) {
if ( console && console.log ) {
console.log( data );
}
});
Make a JS code which would convert the data got in the previous section to a readable html and show it on your page. It should be implemented in the the block where console.log(data) is.
Put that part of code in a setInterval
setInterval(function(){
//$.ajax();
}, 10000);
And be aware that you are gonna go to hell if your request doen't complete in the interval. see this .
I have a better suggestion, again it is same as using setInterval.
setInterval(function () {
if (isActive) return; // so that if any active ajax call is happening, don't go for one more ajax call
isActive = true;
try {
$.ajax("URL", params,function() { isActive = false;//successcallback }, function () {
isActive = false; // error callback
});
} catch (ex) { isActive = false;}
}, 10000);
Your problem is a failure to understand AJAX. Below is a $.post() example.
First let's make the page that you want your Client (the Browser user) to see:
viewed.php
<?php
$out = '';
// you could even do your initial query here, but don't have to
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
#import 'whatever.css';
</style>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='whatever.js'></script>
</head>
<body>
<div id='output'><?php /* if initial query took place */ echo $out; ?></div>
</body>
</html>
Now you need your JavaScript in whatever.js.
$(function(){
function getData(){
$.post('whatever.php', function(data){
// var htm = do a bunch of stuff with the data Object, creating HTML
$('#output').html(htm);
});
}
getData(); // don't need if PHP query takes place on original page load
setInterval(getData, 10000); // query every 10 seconds
});
On whatever.php:
<?php
// $assocArray = run database queries so you can create an Associative Array that can be converted to JSON
echo json_encode($assocArray);
?>
The JSON generated by PHP shows up in the data argument, back in the JavaScript that created your PHP request:
$.post('whatever.php', function(data){

Logout and Delete Cookies [Redirect to main page]

When user clicks the logout button from the main page, the cookies will be deleted and they will be redirected to window.location = url; . Even if user does not login, but instead clicks logout, they will still be redirected to window.location = url;. My codes are as below, I can't seem to logout even if I click the logout button and I will stay at the main page while being logged in. Can anyone tell what is wrong? I am new to JavaScript and I need help regarding this topic.
$('.logout-btn').click(function(e){
e.preventDefault();
if(isset($_COOKIE['REFERER']) && $_COOKIE['REFERER'] != '') {
window.location = url;
}
else {
$.post(outurl, function( data ) {
}).then(function(r){
$('#popup_ok, .x-close').bind( "click", function() {
window.location = url;
});
if(r.result == 1){
popup_msg('Failed', r.msg);
}
else{
popup_msg('Success', r.msg);
setTimeout(function(){
window.location = url;
},2000);
}
});
}
});
try this code this will execute when user close the tab or close the browser it will automatically destroy session and cookies stored
<body onbeforeunload='destroySession()'>
</body>
<script type='text/javascript'>
function destroySession()
{
$.ajax({
url: 'process/logout.php'
});
}
</script>
logout.php
<?php
session_start();
unset($_SESSION['id']);
header("location:../login.php");
?>
specify the path of your file at place of login.php

Backlink check script PHP

I got a script to check if a URL is present in a page. Here it is:
class LP_backlinkchecker
{
var $url;
var $content;
var $links;
var $linktocheck;
function __construct($url, $linktocheck)
{
$this->url = $url;
$this->linktocheck = $linktocheck;
}
function SetLinktocheck($link)
{
$this->linktocheck = $link;
}
function getContents()
{
$this->content = file_get_contents($this->url);
}
function lpFetchLinks()
{
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
preg_match_all("/$regexp/siU", $this->content, $matches);
$this->links = $matches;
return $matches;
}
function check()
{
foreach($this->links[2] as $key => $url)
{
if($url == $this->linktocheck)return TRUE;
}
return FALSE;
}
}
My problem is that the script only works for checking links on the same site. It does not work when the links to check is outside of the website. For example, the script works well to check the link
http://web.com/linktocheck present on the website http://web.com/
If think my $regexp is wrong, do you have some idea of the problem ?
Thanks for your help.
Not sure if I have misunderstood your issue but your code seems to work for me. I wrote you a little unit test that you can now have and expand upon, if you could write a test that does not work I might be able to help more.
class LP_backlinkcheckerTest extends PHPUnit_Framework_TestCase
{
public $l;
public function setUp()
{
$this->l = new LP_backlinkchecker('test.html', null);
}
public function tearDown()
{
}
public function testGetContents()
{
$this->l->getContents();
$this->assertNotEmpty($this->l->content);
}
public function testlpFetchLinks()
{
$this->l->getContents();
$matches = $this->l->lpFetchLinks();
$expected = array(
"http://google.com",
"http://www.bluesnews.com",
"http://www.bluesnews.com/somepage"
);
// 4 things captured by the regex
$this->assertEquals(4, count($matches));
$this->assertEquals($expected, $matches[2]);
}
}
and the HTML file I am using
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Google.com
BluesNews.com
somepage
</body>
</html>
Although it would be better to make your class so that I don't have to supply it a file but that's the way you designed it. I would also suggest perhaps using parse_url to breakdown the url into it's component parts. Your problem may be just that your expecting one string to be equal to the other and there may be a user input error at construct time which your not checking at all.

log out confirmation box in javascript

I have a php code for logout page but i need to have a confirmation box pop-up first if i click the navigation box to logout...if I want to logout or not...can any1 help me?? please
code:
<?php
include("connection.php");
// Delete certain session
unset($_SESSION['username']);
// Delete all session variables
// session_destroy();
$uid = $_POST['uid'];
$stat="UPDATE users SET status='logout'";
mysql_query($stat);
// Jump to login page
header('Location: index.php');
?>
maybe this is what you are trying to achieve?
var logout = confirm("Are you sure to logout?");
if(logout){
location.href = "pathtologout.php";
}
Most simple:
Logout
If you just need a simple confirmation, you can do this
$('#logout').click(function(){
var reallyLogout=confirm("Do you really want to log out?");
if(reallyLogout){
location.href="path/to/logout/file.php";
}
});
If you can't use jQuery(!), you can use pure Javascript to attach the event handler
function logout(){
var reallyLogout=confirm("Do you really want to log out?");
if(reallyLogout){
location.href="path/to/logout/file.php";
}
}
var el = document.getElementById("logout");
if (el.addEventListener) {
el.addEventListener("click", logoutfunction, false);
} else {
el.attachEvent('onclick', logoutfunction);
}

how to get the response from the php page?

I need to send the textbox value on anchor tag click to checkID.php and display the response sent from php page in html page. I tried using javascripts. But the page is redirected to checkID.php page. need to display in the very same html page.
<a href="#" onclick="javascript:fillContent('checkID.php'); ">
Check Availability
</a>
In form action I speceified as checkID.php.
Following is the javascript I used
<script language="javascript">
function fillContent(resource)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", resource, true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4) {
el = document.getElementById('availabilityResponse')
el.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
</script>
below is my php code
<?php
require_once('lib/nusoap.php');
$client=new nusoap_client("http://localhost/server.php?wsdl");
$error = $client->getError();
if ($error) {
return $error;
}
$alias=$_POST['id'];
$response = $client->call("checkAvailability", array("id" => $alias));
if($client->fault)
{
return $client->faultstring;
}
else
{
$error = $client->getError();
if ($error) {
return $error;
}
else {
return $response;
}
}
?>
how to get response and display in html page?
Not sure why its getting redirected, but in your PHP file -
Instead of
return $response;
Use
echo $response;
Always use echo instead of return in ajax cases
That code should not redirect to that page. Cancel the click action and see if that helps.
onclick="fillContent('checkID.php');return false"
I suggest you to use jquery. Its very simple
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#myID").on("click",function(){
$.ajax({ url: 'checkID.php',
type: 'post',
success: function(output) {
$("#availabilityResponse").html(output);
}
});
})
</script>
</head>
<body>
Check Availability
</body>
</html>

Categories

Resources