TYPO3 extension: Accessing the TYPO3 session variable from javascript? - javascript

This may sound a little unprecise, but is it possible to change the TYPO3 session variable
$GLOBALS["TSFE"]->fe_user->setKey('ses', 't_minus', 0);
from javascript somehow for the variable to be processed within a listAction to specify certain records to be shown or not?
In more detail: I work on an extension for a calendar. The calendar is generated in javascript (that's the part i'm not responsible for). The listAction basically generates a JSON object or records which have a unix timestamp within a specific interval (2 weeks in the past, 3 weeks in the future). The javascript has a button "one week forward"/"one week back". One week back should subtract 604800 (1 week) from the session variable, one week forward add 604800 (1 week) to the session variable.
In the listAction the session variable adjusts the timestamp interval (n weeks forward/backward) or rather which records should be put into the JSON object.
Is it possible to access the session variable from javascript or does this violate safety requirements?

It is not possible to change TYPO3 session content directly via javascript. It may be that you can access the PHP session cookie via javascript - I am not quite sure on that -, but the session variables are stored in the TYPO3 DB. They are serialized and encrypted via PHP and you won't be able to get access on these via Javascript. This is only possible via PHP.
What you could do: create oneWeekForwardAction and oneWeekBackAction in your controller. Read your session cookie and modifie it to your needs. These actions can be activated via Ajax. For this to happen you have to create the appropriate links with the f:uri.action in advance in your Fluid template! Place these strings somewhere in your JSON object. Then you can connect these links to the click events.
Don't forget to generate a special AJAX page type with page.config.disableAllHeaderCode. If you search for this and Ajax you will find examples, f.e. this one:
[http://www.sklein-medien.de/tutorials/detail/erstellung-einer-typo3-extension-mit-ajax-aufruf/]
It is from 2016 und uses Extbase/Fluid.

I would create a PHP function to change this session variable (e.g. with eID functionality) and call the function via AJAX in JavaScript.
More see here: https://seethroughweb.com/ajax-with-typo3/
(Sorry, couldn't find a better manual in english, you need to use the new class names)

It's not a question of safety. The idea of a session is, to bind to the same data on the server over a series of multiple HTTP requests. Javascript lives in the Browser. There is no direct access from JavaScript to the data on the server.
If you are responsible for JS only, it's the job of the other person to provide an interface to the session data for you.
And yes, I think it a good idea to synchronise your calculations in the Browser with the data in the server else calendar datas get quickly out of sync. I would even go that far, that the server should be responsible for this kind of calculations, as it is more reliable than JS. So the guy responsible for PHP should do the main job and provide results to you i.e. via AJAX.

Related

Set SESSION on php and remove it via JAVASCIPT [duplicate]

Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

How to save click path as JSON?

Let's say I have a quiz written in JavaScript. There are four different possible answers to each question. The participant clicks his way through the quiz one by one, he can cancel it at any time.
Now I want to save the user's click path including the respective timestamps. My idea is to record the click path as a JavaScript object and to transfer this object to the server via AJAX and save it in a JSON file after each click. Does that make sense?
The tricky things seem to me to be (1) to update the correct object (the correct line(s) in the JSON file) within a quiz session (no session cookies) for each click from the second click and (2) to append a new object for a new quiz session, both, if possible, without reading and rewriting the entire JSON file every time.
Your opinions and ideas are appreciated.
Edit: I have control over the backend and I'm using PHP.
Now I want to save the user's click path including the respective timestamps. My idea is to record the click path as a JavaScript object and to transfer this object to the server via AJAX and save it in a JSON file after each click.
Rather than sending the object to the server via Ajax and saving it in a .json file, you can, more simply, store a JSON (including timestamps) in localStorage and update it there.
See the localStorage API:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
localStorage is both:
more robust / persistent than keeping the data in an object
less elaborate than Ajax-ing data to the server repeatedly

How do you save information in Javascript programs

As it may be obvious from my question, I'm very new to creating javascript programs. However I have made a few small programs and so I understand the basics about creating variables and getting input from the user and such. The question that I've had this entire time and have had some trouble getting a clear answer on is how do you keep that information stored after you close the program?
So for example: If the code has X = UsersName and then the user sets X to "Joe Smith" and quits the program, how can I save that data so that the next time the user opens the program the variable X is already Joe Smith?
(This is my first time using StackOverflow to ask a question so hopefully I worded that correctly and followed the proper format)
Assuming you are executing JavaScript in a browser, like most of JavaScript world, not on a server (using e.g. Node.js).
In this scenario, you can
Save a value to window.sessionStorage, which will be available there until the browser tab is closed (thus, probably not what you're after)
Save a value to window.localStorage, which will be available there until either you or the user delete it explicitly
Let a user download it in a form of a file (then reupload it when they want to resume), using a data URI
Post a value to a program running on a web server (using form submission, XMLHTTPRequest, or Web Sockets), which will store it for you in a more (or less) persistent way (a file, a database, a cookie, a variable)

Save table sorting after page reload

I have webpage with table and javascript that sorts columns (js I found in google). This page have refresh option (every 30 secs). I need to save table sorting after refresh. How can i do it?
You must have some sort of a database.
A popular one is MySQL.
Remember, javascript is browser-side (client-side) language,
and so it is not capable of saving data. (without using HTML5 storage or cookie).
If you want to save it using cookie or html5 storage, look:
http://www.w3schools.com/html/html5_webstorage.asp
http://www.w3schools.com/js/js_cookies.asp
If you have access to PHP (at least you've tagged this with PHP) and you don't need to save the sorting permanently, try using sessions.
In essence:
Set table sorting with JavaScript on the page where the table is displayed (this is what you currently have).
Call PHP via AJAX, submit the selected sorting method/type as a parameter.
PHP script receives the POST and initiates or reloads a session (session_start()).
PHP saves the sorting method into the session $_SESSION['table_sort_method'] = $sort_method; ($sort_method should be received from the AJAX POST, 'table_sort_method' is just an example array key name).
Now when the page viewer returns to the table page, you can lookup the sorting method from $_SESSION and use it when the table is initially displayed.
Remember to call session_start() before any HTML is output to get access to the correct $_SESSION data.
If you need this to be permanent, you can use the above logic but replace the PHP session related parts with database interactions of your choice.

Passing a variable from one page to the next page

I am developing a Question & Answer website where a user is presented five puzzles on a page and the score is calculated using JavaScript as he attempts the questions on the page. The score is saved in a Javascript variable score. I have a paging system like this:
Now when the user clicks on 3 I want to send the variable score to the next page, where I have require scoreUpdateInDatabase.php on each such page such that the score of previous page is made permanent to the databse and the following PHP script presents him the next 5 questions.
How can I pass that score variable in secure way? I can't use GET because the user will modify it. I am satisfied with POST if this can be used, even though POST data can be modified but I just want minimal security.
P.S. Please do not suggest making AJAX call where in one side I will send score and while returning carries next 5 questions. I don't want to use AJAX to refresh content because it is not SEO friendly.
The simplest solution would be cookie based. Writing the value to a session cookie and the reading it.
You could use jquery cookie. It also gives you the option to require https if desired.
Save it in a session. POST would work equally well in this particular case but my preference would be storing it in the session.
The only secure way to do this is to pass the actual answers to the server using a POST or AJAX, do the calculation of the score also on server side and keep it in a SESSION variable.
More information on sessions in PHP
Try looking into Jquery - You should be able to return the value to the server scripting language (as you listed PHP as a tag, I assume you're using PHP). By using Jquery, you can get the javascript variable to the form BEFORE submitting the form to the next page.
Assuming you have used PHP to generate the form to submit initially rather than create the form in javascript. I would use Jquery - to get this file ( http://jquery.com/ ) and to include("jquery.js"); etc... in your PHP script for it to be used.
I would then convert the javascript variable(s) to a php variable and assign this to a hidden field in the form to be submitted to the next page using a $_POST[] variable.
However It will not be SEO friendly (POST and SESSION is not SEO friendly, but you should use them, continue reading)
We are talking of a game. No-one want that the Search engine index the last page of a game... because everyone can search on google (for example) for the last page of your game without playing.
You have to use ajax or post, but don't let google index every page of your game. It's nonsense.
Only the first page of your game should be indexed.

Categories