Why my confirm "alert" don't work on my code? - javascript

This is a page of a web app, and the job is simple:
I can see the "alert" that asks me whether I want to confirm or not. Based on the answer, I move to other pages.
If i sent my "if" cicle, the "alert" it's showed. This is the code
<?php
session_start();
include('../Model/gestoreAccessi.php');
include('connect.php');
?>
<script>
let result = confirm("Sei sicuro di voler procedere?");
</script>
<script>
if(!result)
result = <?php header('Location: http://www.teamjg.altervista.org/Matteo/navbar.php');?>
else
<?php
session_start();
session_unset();
session_destroy();
header('Location: http://www.teamjg.altervista.org/Matteo/index.html');
?>
</script>

So, before I answer your question; just a note. PHP and Js will run on different machines (even though you're testing it on your localhost, still consider them as different machines)
All PHP code is run, and executed on the backend before anything is sent to your browser, after which js code is executed. PHP does not understand JS syntax, it will only look at <? and ?> tags and execute everything inside them.
<?php
session_start();
include('../Model/gestoreAccessi.php');
include('connect.php');
?>
<script>
let result = confirm("Sei sicuro di voler procedere?");
</script>
<script>
if(!result)
result = <?php header('Location: http://www.teamjg.altervista.org/Matteo/navbar.php');?>
else
<?php
session_start();
session_unset();
session_destroy();
header('Location: http://www.teamjg.altervista.org/Matteo/index.html');
?>
</script>
When this code is being sent by XAMPP (or whatever engine you use), the PHP is first executed which will make the code look like this:
// Session will be started
// contents of ../Model/gestoreAccessi.php will be copied and run
// contents of connnect.php will be copied and run
<script>
let result = confirm("Sei sicuro di voler procedere?");
</script>
<script>
if(!result)
result = //The header is already set
else
// Location is already set
</script>
So this is undefined behaviour as you are sending two header tags with different locations, my best guess is it will redirect to http://www.teamjg.altervista.org/Matteo/index.html.
One thing you could do as a hotfix is set window.location.href if you want to redirect your user to some other website. Read this.

Related

How to connect between the sessionStorage in PHP to JS

I am trying to transfer data in my PHP (html) page, befor the HTML is loaded, so I will be able to deal with it after the page is loaded in my JS file.
my php look like this:
<?php
/*some php code*/
$dataFromDataBase = "..";
session_start();
$_SESSION['data'] = $dataFromDataBase;
if(isset($_SESSION['data']))
echo $_SESSION['data'];
else
echo "<br>False";
?>
<html>
<!--My Html code..-->
</html>
the "if" condition is there now to check if the session was created in the php.
now it echo me the data, so it's meen the session exist.
my JS look like that:
if(sessionStorage.getItem("data")){
//do some thing..
}else{
alert("the data isn't set.");
}
and the data isn't exist... I've tride to alert the data, and it send me "null"..
they offered me to output into JS directly like that:
<script>
var fromserver="<?php
/*some code.. */
echo "**BIG DATA**";
?>";
but it is just untidy code.. and the data is pretty big so I can't use coockies
$_SESSION and sessionStorage are completely different.
sessionStorage saves data like $_SESSION except a sessionStorage variable is set on the client's side. $_SESSION is like sessionStorage so I see your misunderstanding, however, this sets data on the server-side and does not cross over to sessionStorage.
If you really need that $_SESSION data in sessionStorage, you can echo a script which sets the sessionStorage to your $_SESSION data. Here's a very simple example below.
<?php session_start;
$_SESSION['data'] = "yourdata";
echo '<script> sessionStorage.setItem("data", "' . $_SESSION['data'] . '");</script>';
//Display 'data'.
echo '<script> alert(sessionStorage.getItem("data")); </script>';
EDIT: To make it more clearer, notice how $_SESSION is done in PHP (server-side) and sessionStorage has to be set in JavaScript with the <script> tags. Below is a solution to your problem.
<?php
/*some php code*/
$dataFromDataBase = "..";
session_start();
$_SESSION['data'] = $dataFromDataBase;
if(isset($_SESSION['data']))
{
echo '<script> sessionStorage.setItem("data", "' .$_SESSION['data'] .'");</script>';
}
else
{
echo "<br>False";
}
?>
<html>
<!--My Html code..-->
</html>
Creating executable JS code from user provided data is a major security issue, so you should avoid the statements like var someJsVar = '<?= $somePhpVar;?>;'. Injecting malicious code could be a simple as '; malicious-code-here //
https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)
https://www.owasp.org/index.php/XSS_Attacks
It would be more secure to have your page make an API call on page load, which would return your data for sessionStorage encoded as JSON. This way the browser will see a variable containing the user data, and not the raw data itself.
#Initial page
<body>
<script>
$.GET("/session-storage.php").success(function(response){
sessionStorage.setItem("data", response);
});
</script>
</body>
#API Call (session-storage.php)
<?php
$dataFromDataBase = "..";
echo json_encode($dataFromDataBase);
?>
you can take data from php variable and use it in JS.. like this
var sessionData = <?php echo $_SESSION['data'];?>
if (typeof sessionData != "undefined" && sessionData == null){
//do some thing..
}else{
alert("the data isn't set.");
}

Javascript code not working inside PHP

This is the code I am executing inside PHP condition
<?php
if(is_null($model)) {
echo "<script>window.parent.closeIframe(true)</script>";
}
?>
It doesn't work even If I put alert or calling a function inside my PHP condition.
Is it possible to run a Javascript code inside PHP ?
Is there any PHP extensions needed to be enabled ?
Was working on a recent project to execute JavaScript after PHP was finished executing. Try placing the script tag after the PHP tag:
test.php:
<?php
echo "hello";
include("example.html") // To insert HTML page
?>
<script>
alert("hello");
</script>
This worked for me. You can try it. I forced $model to be null.
<?php
$model = null;
if(is_null($model)) {
echo "<script>alert('Hello World')</script>";
}
?>
You can't call close from client Javascript from server PHP.
but you can call from HTML client. put close in bottom of HTML body tag
and make sure Javascript is turned on in your browser.
Hi if you are executing a query and then checking if result is null then this script to run then please correct. PHP is_null is true when it get NULL php datatype and a query never returns this. So if i am right then you can use this one this is my example which i used to check your method.
<?php
$con = mysqli_connect("localhost","root","","user") or die("error");
$res = mysqli_query($con, "select * from user where id =-99");
$model = mysqli_num_rows($res);
if(empty($model)) {
echo "<script>window.parent.closeIframe(true)</script>";
}
?>
just to check you can refer
$model = 0;
<?php
if(empty($model)) {
echo "<script>alert("hello")</script>";
}
?>

PHP refreshing using jQuery doesn't work in IE

I wanted to create a function in javascript/jQuery, that uses php script to refresh some data on my website. I'm using it like this:
function aval()
{
...
$("#dost").load("readadmin.php?date="+dzien+"&diff="+diff+"&dtyg="+d);
setTimeout(aval,200);
}
where #dost refers to some div at the end of my site
Then, my readadmin.php file looks like this:
<?php
$diff=$_GET["diff"];
$name = $_GET["date"];
$dtyg = $_GET["dtyg"];
$plik = fopen("myfile","r");
$tekst = fread($plik,filesize("myfile"));
fclose($plik);
$bookings = explode(";;;;", $tekst);
for ($i=0; $i<(sizeof($bookings)-1); $i++)
$data[$i] = explode(":::",$bookings[$i]);
echo "<script>";
// here I'm echoing some javascript code, that basically changes styles on my page,
//depending on my variables and data from a file
echo "</script>";
?>
Also, on my site (admin.php) I use login, so my site looks like this:
<?php
session_start();
if(!session_is_registered('pass'))
header('location: login.php');
?>
...html code
login.php:
..something not important, forms to get $_POSTs etc..
<?php
if ($_POST["login"] == $login && $_POST["pass"] == $pass)
{
session_register('login');
session_register('pass');
header("location: admin.php");
}
?>
Now, everything works great on Chrome or Firefox, but not on IE. When I change data in my file, IE doesn't react to this, and keep displaying old data. When I put session_start() and session_destroy() at the begining and end of readadmin.php, then data is refreshing properly, but whatever action I do, it logs me out. Nothing strange here, I start a new session every 200ms so I get kicked.
One more thing: when I'm changing data that goes to readadmin.php from site, it displays proper data back, and then immediately changes to old data.
Please help.
You can add timestamp to url so the browser will not cache the file:
$("#dost").load("readadmin.php?date="+dzien+"&diff="+diff+"&dtyg="+d+"&t="+Date.now());

Header location is not working on live server

I Have one registration and payment page. program flow is like registration > confirmation > payment. After validation and calculation in registration page need to go to confirmation page.
My code is
<?php
ob_start();
session_start();
include("header.php");
include("ini.php");
date_default_timezone_set('Asia/Brunei');
header('Cache-Control: max-age=900');
if (isset($_POST['submit'])) {
$error = 0;
//validations
if ($error <= 0) {
//do some calculation
header('location:confirm.php');
}
}
<?php
ob_flush();
?>
Control entered in to if ($error <= 0) clause, but stay on the registration page.
I tried many ways like
header('location:confirm.php', true, 302);
instead of
header('location:confirm.php');
removed
ob_start() and ob_flush()
add exit() after header()
then it goes to blank page.
Also try to use
echo '<script type="text/javascript">';
echo 'window.location.href="confirm.php";';
echo '</script>';
Then the control goes to confirmation page but url seems to be as registration.php
But header('location:confirm.php'); is working fine in my local server. Anybody please help me to resolve this issue.. Is there any alternate way for header(). Looking forward to you guys.. Thanks
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Also try to change header('Location:confirm.php');
(Note L is capital since its work in your local server may be problem with strict php type try this once)
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'confirm.php';
header("Location: http://$host$uri/$extra");
use ob_end_flush() at the end. This should work like charm.
i had the same issues for years but today i discovered that u don't have to have any html or blank space before the header word .Try it out

PHP variable is empty when called in jQuery script

I'm having a little trouble calling a PHP variable into a jQuery script. Basically, I run a few functions to determine if a user is logged in and, if so, store that as $loggedin=1. If a person that is on a page is NOT logged in, when a button is clicked I want them to be prompted to sign in (I'll obviously still ensure the user is ACTUALLY logged in on the server side before any processing of data). I searched around, and found the easiest way to get that information over to jQuery is to create the script as a PHP file so I can echo it into the script. Here is the high level code I'm using:
Call up the script:
<?php
$loggedIn = 1;
<script src="../buttonScript.php"></script>
?>
Script:
<?php header("Content-type: application/javascript"); ?>
var buttonScript = function(){
var loggedIn = <?php if($loggedIn===1){echo "1";}else{echo "0";} ?>;
$("#button").click(function(){
alert(loggedIn);
});
};
$(document).ready(buttonScript);
When I click the button in a situation where $loggedIn is equal to 1, the alert gives me 0. In fact, if I simply echo $loggedIn in the script itself, the value is completely empty and the script errors out and won't pop up an alert at all. I'm confident that the PHP variable $loggedIn actually has a variable, since if I echo the variable right before the script is called, I successfully see the number 1. What am I missing here?
Note: added a couple lines in the script calling just for clarity.
Try this
<?php
$loggedIn = 1;
require("/path/buttonScript.php");
?>
buttonScript.php
<script type="text/javascript">
var buttonScript = function(){
var loggedIn = <?php echo $loggedIn; ?>;
$("#button").click(function(){
alert(loggedIn);
});
};
$(document).ready(buttonScript);
</script>

Categories

Resources