How to connect between the sessionStorage in PHP to JS - javascript

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.");
}

Related

Convert WebStorage (JS/JQuery) content into Blade-ready variable

so I'm currently saving local data via WebStorage. Was wondering if there's a way to convert it to a Laravel Blade-ready variable upon page load. Here's what I've done so far.
$(document).ready(function () {
var data = JSON.parse(localStorage.getItem("data"));
// initialize php code
<?php $var = ?> data <?php ; ?>
});
However this doesnt work since it breaks PHP ruling

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

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.

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());

Redirect a page with PHP and send a JSON string to Javascript

Right now I have a php file that recieves a string from a search bar on page1 of my website. It queries the data bases and creates a JSON string of results. I can then use PHP to redirect my website to page2 (The search results page). How can I receive that JSON string in the Javascript of page2?
First you need a PHP file that will encode json code . Make a file like this:
http://localhost/project/myjs.php
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Then your JavaScript (in this example I use jQuery):
$.getJSON('http://localhost/project/myjs.php', function(data) {
console.log(data);
});
This should be a start to get PHP arrays in to your JavaScript.
To redirect browser to another page you have to use header function
header:('Location: http://example.com/page2.php');
You can store data in $_SESSION array between pages like that:
page1.php
session_start();
$_SESSION['array'] = array('foo'=>$bar);
page2.php
session_start();
echo json_encode($_SESSION['array']);
page1.php:
<?php
$my_array = array('foo'=>$bar);
$json_data = json_encode($my_array);
header:('Location: http://example.com/page2.php?data='.$json_data);
?>
page2.php
<?php
$data_get = $_REQUEST['data'];
?>
<script type="text/javascript">
var mydata =<?php echo $data_get; ?>;
</script>

How to access variable declared in PHP by jquery

For example i declare some variable like test in server side of my PHP
echo('var test = ' . json_encode($abc));
Now i want to use this test variable in Jquery ..how can i use it?
What function do i need to use it?
For Example i have:
I have back end PHP code something like this
$abc = no
echo "var test= ".json_encode($abc);
I want jquery to do the following action(client side)
$(document).ready(function(){
function(json) {
if($abc == no )//this i what i want to be achieved
}
}
I think, you dont understand the diference between frontend (JavaScript) and backend (PHP). You can not directly access php variables from javascript. You need to make Ajax-request to some php file, that will return some data that you need in format that you specify.
for example:
<?php
$result = array('abc' => 'no');
echo json_encode($result);
?>
This is serverside script called data.php. In Javascript you can make so:
$(document).ready(function(){
$.getJSON('data.php', function (data) {
if(data.abc === 'no') {
your code...
}
});
}
You're comparing the wrong variable:
<?php
echo <<<JS
<script type="text/javascript">
var test = {json_encode($abc)};
$(document).ready(function(){
if(test == 'no' )
// here you go
}
});
</script>
JS;
If you really wanted to (though I don't think this is a very good practice), you could echo the PHP variable's value into a javascript variable like this:
<script type="text/javascript">
var phpValue = <?php echo $abc; ?>;
alert(phpValue);
</script>
I can see this being dangerous in many cases, but what this effectively does is echo the value of $abc onto the page (inside of your script tags of course). Then, when the javascript it run by the browser, the browser sees it like this:
<script type="text/javascript">
var phpValue = no;
alert(phpValue);
</script>
This is very basic, but you get an idea of what you could do by using that kind of code.

Categories

Resources