php echo javascript alert() not working - javascript

I would like to display a popup message when user is logged out, so I use
echo "<script>alert(\"You are logged out\");</script>";
But it doesn't work.
Below is my coding. Is there any logic problem in my coding?
<?php
session_start();
if(isset($_SESSION['Username']) == "admin")
{
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
#import "../CSS/Style.css";
#import "../CSS/Admin.css";
</style>
<title>Admin Home Page</title>
</head>
<body>
<div class="body"></div>
<?php
if(isset($_GET['id']) == "logout")
{
session_destroy();
echo "<script>alert(\"You are logged out\");</script>";
header("Location: ..\Main.php");
}
else
{
?>
<div class="menu">
Manage Staff
</div>
<div class="menu2">
Manage Account
</div>
<div class="logout">
Logout
</div>
<?php
}
}
else
{
?>
<center>
<p style="font-size:50px; font-weight:bold">Access Denied</p>
<p style="font-size:18px">Your request for this page has been denied because of access control</p>
</center>
<?php
}
?>
</body>
</html>
The session will be destroyed and will also redirect to Main.php, just the alert() will not come out.

You're doing an echo and then writing a relocate header. If you did your relocate in the javascript (after the user clicked the alert), it would probably work the way you expect it to.
echo "<script>alert('You are logged out'); window.location.href='..\Main.php';</script>";
Also, the way that you use isset will cause problems because isset returns true or false (it checks if a value is present), rather than returning the value.
So instead of
if(isset($_SESSION['Username']) == "admin")
You need to do:
if(isset($_SESSION['Username']) && $_SESSION['Username'] == "admin")

header("Location: ..\Main.php"); tells the browser to go to another page before it even shows the page... if you want the user to see the alert, try this:
session_destroy();
echo "<script>";
echo "alert('You are logged out');";
echo "window.location = '../Main.php';"; // redirect with javascript, after page loads
echo "</script>";

use this it will solve your problem!! first change your code from
if(isset($_SESSION['Username']) == "admin")
{
to
if(!empty($_SESSION['Username']) && ($_SESSION['Username']=="admin")){
and than use following code
if(!empty($_GET['id']) && ($_GET['id']=="logout"))
{
session_destroy();?>
<script>
alert("You are logged out");
window.location.href='..\Main.php';
</script>
<?php }?>

Try,
This must work,
And remove php header, replace with the following code.
echo "<script>alert('You are logged out');
location.href='..\Main.php';
</script>";

Related

Newbie needs to force php page reload once

I have this php file which I am using to control relays attached to the gpio pins of a Raspberry pi. I works well except that the icons do not update as desired when the gpio pins change state. THey do update as desired if I click the RELOAD button on the browser. I have tried using:
location.reload(true) but it only works if I put it in the html portion of the page code as its own button. I want the location.reload(true) to execute whenever I click one of the gpio icons. Can someone help me with this? Thanks in advance from a newbie.
Here is the php code I am using:
<!DOCTYPE html>
<!--TheFreeElectron 2015, http://www.instructables.com/member/TheFreeElectron/ -->
<html>
<head>
<meta charset="utf-8" />
<title>Antenna Relays</title>
</head>
<body style="background-color: black;">
<h1><p style="color:white"><font size="7">
    ANTENNA SELECTOR
</p>
</font></h1>
<!-- On/Off button's picture -->
<?php
$val_array = array(0,0,0,0);
//this php script generate the first page in function of the file
for ( $i= 0; $i<4; $i++) {
//set the pin's mode to output and read them
system("gpio mode ".$i." out");
exec ("gpio read ".$i, $val_array[$i], $return );
}
//for loop to read the value
$i =0;
for ($i = 0; $i < 4; $i++) {
//if off
if ($val_array[$i][0] == 0 ) {
echo ("<img id='button_".$i."' src='data/img/red/red_".$i.".jpg' onclick='change_pin (".$i.");'/>");
}
//if on
if ($val_array[$i][0] == 1 ) {
echo ("<img id='button_".$i."' src='data/img/green/green_".$i.".jpg' onclick='change_pin (".$i.");'/>");
}
}
?>
<!-- javascript -->
<script src="script.js"></script>
</body>
</html>

pop up message on success full submit

i am creating a blog posting page for practice.
1) i want a pop up window 'javascript' on success full data submitting to phpmyadmin.
2) same on failure a popup window.
3)where exactly we should close the mysqli connection mysqli_close(); in a isset codding.
i have tried all onclick, onsubmit, two function on one onclick but all in vain
reasons: two javascripts function were not working on one button.
while onsubmit code typed the popup window appears but data does not success fully submits to phpmyadmin.
<html>
<head>
<title>
</title>
</head>
<link href="blogsup-main.css" type="text/css" rel="stylesheet"/>
<link href="blogsup.css" type="text/css" rel="stylesheet"/>
<body onload="refresh();">
<center>
<form method="post">
Name
Category
<option>Education</option>
<option>Society</option>
<option>Politics</option>
<option>Business</option>
<option>IT</option>
<option>Book</option>
<option>Other</option>
Heading
Sub heading *optional
Blog
*Send Email
</form>
</center>
<div id="popupdiv" class="popup-area">
<div class="popup-content">
<span class="close">×</span>
<center>
Blog Created Success Fully!pending approval.
Proceed
</center>
</div>
</div>
</body>
</html>
<?php
$user='root';
$password='';
$db='blogsup';
$con=mysqli_connect('localhost',$user,$password,$db);
mysqli_select_db($con,$db);
if(isset($_POST['submit'])){
$bloggername=$_POST['bloggername'];
$category=$_POST['category'];
$heading=$_POST['heading'];
$subheading=$_POST['subheading'];
$textarea=$_POST['textarea'];
$que="insert into blogposting (bloggername,category,heading,subheading,blogdate,blog) values ('$bloggername','$category','$heading ','$subheading', now(),'$textarea')";
$run=mysqli_query($con,$que);
if($run){
echo '<script type="text/javascript">
var popupdiv = document.getElementById("popupdiv");
popupdiv.style.display = "block";
return false;
</script>';
} else{
echo"Failed";
}
}
mysqli_close($con);
?>
<script type="text/javascript">
var nametextbox = document.getElementById('nametextbox');
var heading= document.getElementById('heading');
var blog = document.getElementById('blog');
var span = document.getElementsByClassName('close')[0];
function refresh(){
nametextbox.value='';
heading.value='';
subheading.value='';
blog.value='';
}
span.onclick = function() {
popupdiv.style.display = "none";
nametextbox.value='';
heading.value='';
subheading.value='';
blog.value='';
message.innerHTML = '';
}
</script>
When you submit a form there is no success or failure.You shouldn't add php and html and js code in the same page.Add the php code to php file which will be your action
e.g
<form action="anyfile.php" method="post">
In the php file add your business logic, like connect to db, execute queries and close the db connection.when the insert query is executed without errors then send a redirect back (yourMainPage?message='ok') to show a successful message like
<?php if(isset($_GET('message') == 'ok'){ ?>
<p>Data successfully inserted</p>
<?php } ?>
Also, your code should be more tidy. Hope i helped.

open a link in a different tab

I have a button that allows authentication from twitter, everything works properly, but the only issue is that i wish to open the login-twitter.php page on a different tab, i tried using window.open in place of header but it didn't work. can anyone tell how it can be done
<?php
ob_start();
session_start();
if (isset($_SESSION['id'])) {
header("location: u_tasks.php");
}
if (array_key_exists("login", $_GET))
{
$oauth_provider = $_GET['oauth_provider'];
if ($oauth_provider == 'twitter')
{
header("Location: login-twitter.php");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<?
echo "<div class='col-md-9'>";
echo "<a href='?login&oauth_provider=twitter'><button style='background-color:#1dcaff; border-color:#1dcaff; color:white; height:30px; border-radius:10px;'>Go To Twitter</button></a>";
echo "</div>";
?>
</body>
</html>
i think it is helpful to you.
<button style='background-color:#1dcaff; border-color:#1dcaff; color:white; height:30px; border-radius:10px;'>Go To Twitter</button>
using header("Location:..."); can only do redirects. As far as I know, you'll have to do some amount of javascript or html to achieve your goal. Another problem is that browsers like to block automatically opened popups because 99% of the time automatic popups are used only by spammers. However, I'll show you a way to attempt to do this anyways:
<?php
$usingTwitter=0;
ob_start();
session_start();
if (isset($_SESSION['id'])) {
header("location: u_tasks.php");
}
if (array_key_exists("login", $_GET))
{
$oauth_provider = $_GET['oauth_provider'];
if ($oauth_provider == 'twitter')
{
$usingTwitter=1;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
<?php
if($usingTwitter){
echo "window.open('login-twitter.php');";
}
?>
<script>
</head>
<body>
<?
echo "<div class='col-md-9'>";
echo "<a href='?login&oauth_provider=twitter'><button style='background-color:#1dcaff; border-color:#1dcaff; color:white; height:30px; border-radius:10px;'>Go To Twitter</button></a>";
echo "</div>";
?>
</body>
</html>
Make sure you turn off popup blocking in your browser for this to work though!

JS script function not working in php

Here is my JS function:
function checkError() {
var field = 'error';
var url = window.location.href;
document.write('test');
window.alert('please work');
if(url.indexOf('?' + field + '=') != -1)
document.write('The username and password do not match. Do not use your full email.');
return true;
}
and then in my body paragraph I have:
<?php echo '<script> checkError();</script>' ?>
It doesn't have any errors calling it. But the function does nothing on my page. Any thoughts? I've tried putting the JS script in the page and in a JS file and correctly called for its inclusion.
Full script:
<html>
<head>
<meta charset="UTF-8">
<title>Secure Login</title>
<script type="text/JavaScript" src="js/functions.js"></script>
<link href="stylesheets/mainStyle.css" rel="stylesheet" type="text/css">
<link href="stylesheets/formStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php include('header.php'); ?>
<div id="mainContent">
<h1>Member Login</h1>
<div id="mainParaText">
<?php echo '<script> checkError();</script>' ?>
</div>
</body>
</html>
TURNS OUT JS Function is UNDEFINED. Ugh, can't figure out why (thought I fixed this problem a while back lol)
try like this:
<html>
<head>
<meta charset="UTF-8">
<title>Secure Login</title>
<script type="text/JavaScript" src="js/functions.js"></script>
<link href="stylesheets/mainStyle.css" rel="stylesheet" type="text/css">
<link href="stylesheets/formStyle.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
function checkError(){
var field = 'error';
var url = window.location.href;
document.write('test');
window.alert('please work');
if(url.indexOf('?' + field + '=') != -1)
document.write('The username and password do not match. Do not use your full email.');
return true;
}
<?php
echo "checkError();";
?>
</script>
</head>
<body>
<?php include('header.php'); ?>
<div id="mainContent">
<h1>Member Login</h1>
<div id="mainParaText">
<?php echo '<script> checkError();</script>' ?>
</div>
</body>
</html>
JS is client side and PHP is server side.
That means that everything in PHP code will be processed on server and then "echoed" to your browser where you get undefined error.
When debugging this you should always check source code in the browser first so you see exactly what your server echoed.
I'm guessing a bit but try with double quotes instead of single.
And not related to the question ...
You are checking username and password with JS? How exactly will you do this? With ajax call back to the server? If you check with JS that means password should be in the source code somewhere and that is NOT secure. Username / pass validation should always be made on serverside (either with ajax request or usual submit form).

why is my jquery function not loading on page start?

I have a jquery function.
I also have a variable, $id_number.
If the value in variable exists:
I want the jquery function to load. This is a modal that should pop up on page start.
<? if(isset($id_number))
{ ?>
jQuery(document).ready(function(
<? }
else
{ ?>
jQuery(function($){
<? } ?>
// code
});
why is my function not loading on page start? What am i doing wrong?
This should work
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<? if(isset($id_number))
{ ?><script>
alert('dummy');
</script>
<? }
else
{ ?>
<script>
alert('data');
</script>
<? } ?>

Categories