Set Session variable using javascript in PHP - php

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;
}
?>

Related

Populate PHP variable with AJAX?

Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.

Precedence Order Javascript / PHP / Jquery Json - Get browser res from user

I'm trying to do something that goes far over my current skills yet I believe I can do it, I would be imensely thankfull if you point me to an already developed script for this matter.
My question comes from what runs first? Javascript or php? because I need to asynchronosly include a php file into the page.
My idea is this, if user has a screen width wider then 1024, draw an extra fixed position div, if not, don't draw it. That div is supposed to take in a flash object with a clickable link.
My idea would be to:
Get resolution with javascript.
Use jQuery to send ajax json var into .php file that stores res vars into a session cookie.
Read the cookie with php, decide to include the extra .php file or not. That file should then eco the extra div with flash object.
Is this possible? Is there an easier way? Since this is to include in a Zencart personal store of mine, does it conflicts with the zencart cookie session or can a user have more then 1 type of session cookie per website? it can right?
Best Regards, any help appreciated,
Joricam
Yes, it's possible - but now in the way you're describing. PHP runs server side and Javascript runs client side, i.e. PHP is executed before any Javascripts. However, nothing says you cannot do this only with Javascript - and it would actually be trivial to solve with jQuery (as you tagged the question with it). Just let your Ajax called PHP-page return the inline HTML, and print it with jQuery instead. No need for cookies, either.
PHP runs first because the page hasn't loaded yet and javascript is run user-side, but once the page is loaded, ajax allows you to make calls to a php script and recieve a result that you can then add to the page via javascript.... so yes it's doable:)
Sessions can contain as many keys as you need them to, just name them something specific
<script language="javascript">
if (window.location.search == "") {
window.location.href = window.location + "?width=" + screen.width + "&height=" + screen.height;
}
</script>
This will redirect the page you try to access to the same page but sending parameters to the page.
Then you would be able to:
<?php
$width = $_get['width'];
$height = $_get['height'];
?>

How to query database using javascript?

Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.

Pass vars from php to js without ajax

Lets say I have a php page... I want the javascript in that page to access some user information variables (after logged in), such as userid, email, etc. If I use ajax, then it will take an extra half second, because the page has to load, then wait for ajax to go get those variables, so I'd rather embed it in the page, but that seems questionable as far as security to embed an email in the source.
Here are my options can you think of a better way?
1 - Embed the data into the php on the first request
<html>
<script>
user_email='<?php echo $user_email; ?>';
</script>
2 - Have data load separately from a js/php file so its not in original page source
<html>
<script src="userdata.js.php"></script>
--- userdata.js.php ---
user_email='<?php echo $user_email; ?>';
3 - Request data via ajax after page loads (would be slower)
<html>
<script>
$(function(){
$.post('getuserdata.php',[],function(result){
userdata=result;
});
});
</script>
Another option that you might consider is using JSONP to asynchronously call a function once the AJAX loads.
HTML
<script type="text/javascript">
function handle_response(response)
{
// do whatever you want with the response
// you get a json object here that looks like
// { id: 1, username: 'jimmy' }
}
</script>
<script type="text/javascript src="/path/to/ajax/script.php"></script>
script.php
<?php
$arr = array('id' => 1, 'username' => 'jimmy');
$param = json_encode($arr);
header("Content-type: text/javascript");
echo "handle_response({$param})";
exit;
So now, once that valid javascript from script.php finishes loading it immediately calls your function that you defined client-side. This keeps your information out of the initial HTML source and you could even put that script behind an https without doing that for the rest of the site.
I always use the first step
var myvar = <?php echo $myvar; ?>;
People are rather accustomed with ajax nowadays and a circle saying loading, is not that uncommon. On the other hand if you can embed the data that's just as good. Making a separate file is even better. You should be careful what kind of info you give out though, you could use SSL to make it more secure.
All three are viable... depends on who you're trying to protect the data from. The user that called the page will have access to the information one way or another... so go for the more reliable implementation.
I don't like embedding information in the page for security reasons. At some point in time it is just going to be too easy to store something that shouldn't be there. You have two decent options that occur off the top of my head:
Perform the ajax call during the page load (body onload=ajax call) (more secure)
Store them in the cookie for the site (less secure)
I typically use option #1.
seems questionable as far as security to embed an email in the source.
Retrieving the email via ajax vs embedding it directly in the source suffer from the same security problem: someone sniffing traffic could get the email. To avoid this you would need to either
Figure out a way to not send the email to the client in the first place.
Only send the email address to the client over https
I imagine lots of websites just punt on this issue and send the email to the client unencrypted.

Setting a PHP $_SESSION['var'] using jQuery

I need to set a PHP $_SESSION variable using the jQuery. IF the user clicks on an image I want to save a piece of information associated with that image as a session variable in php.
I think I can do this by calling a php page or function and appending that piece of info to the query string.
Any ideas. I have found little help through google.
thanks
mike
You can't do it through jQuery alone; you'll need a combination of Ajax (which you can do with jQuery) and a PHP back-end. A very simple version might look like this:
HTML:
<img class="foo" src="img.jpg" />
<img class="foo" src="img2.jpg" />
<img class="foo" src="img3.jpg" />
Javascript:
$("img.foo").onclick(function()
{
// Get the src of the image
var src = $(this).attr("src");
// Send Ajax request to backend.php, with src set as "img" in the POST data
$.post("/backend.php", {"img": src});
});
PHP (backend.php):
<?php
// do any authentication first, then add POST variable to session
$_SESSION['imgsrc'] = $_POST['img'];
?>
Might want to try putting the PHP function on another PHP page, and use an AJAX call to set the variable.
Whats you are looking for is jQuery Ajax. And then just setup a php page to process the request.
A lot of responses on here are addressing the how but not the why.
PHP $_SESSION key/value pairs are stored on the server. This differs from a cookie, which is stored on the browser. This is why you are able to access values in a cookie from both PHP and JavaScript.
To make matters worse, AJAX requests from the browser do not include any of the cookies you have set for the website. So, you will have to make JavaScript pull the Session ID cookie and include it in every AJAX request for the server to be able to make heads or tails of it. On the bright side, PHP Sessions are designed to fail-over to a HTTP GET or POST variable if cookies are not sent along with the HTTP headers.
I would look into some of the principles of RESTful web applications and use of of the design patterns that are common with those kinds of applications instead of trying to mangle with the session handler.
I also designed a "php session value setter" solution by myself (similar to Luke Dennis' solution. No big deal here), but after setting my session value, my needs were "jumping onto another .php file". Ok, I did it, inside my jquery code... But something didn't quite work...
My problem was kind of easy:
-After you "$.post" your values onto the small .php file, you should wait for some "success/failure" return value, and ONLY AFTER READING THIS SUCCESS VALUE, perform the jump. If you just immediately jump onto the next big .php file, your session value might have not become set onto the php sessions runtime engine, and will you probably read "empty" when doing $_SESSION["my_var"]; from the destination .php file.
In my case, to correct that situation, I changed my jQuery $.post code this way:
$.post('set_session_value.php', { key: 'keyname', value: 'myvalue'}, function(ret){
if(ret==0){
window.alert("success!");
location.replace("next_page.php");
}
else{
window.alert("error!");
}
});
Of course, your "set_session_value.php" file, should return 'echo "0"; ' or 'echo "1"; ' (or whatever success values you might need).
Greetings.
in (backend.php) be sure to include include
session_start();
-Taylor
http://www.hawkessolutions.com
Similar to Luke's answer, but with GET.
Place this php-code in a php-page, ex. getpage.php:
<?php
$_SESSION['size'] = $_GET['size'];
?>
Then call it with a jQuery script like this:
$.get( "/getpage.php?size=1");
Agree with Federico. In some cases you may run into problems using POST, although not sure if it can be browser related.
It works on firefox, if you change onClick() to click() in javascript part.
$("img.foo").click(function()
{
// Get the src of the image
var src = $(this).attr("src");
// Send Ajax request to backend.php, with src set as "img" in the POST data
$.post("/backend.php", {"img": src});
});

Categories