Jump to content

Updating PHP session variable from client side JavaScript


Cyburg

Recommended Posts

Hi all,

 

I am new to AJAX, and am having difficulty working out if what I want to achieve is even possible; I would be most grateful if someone could give me some pointers, so that I can stop wasting my time thrashing around with something I am struggling to understand as yet....

 

....I have some JavaScript on a page which generates a variable that I need access to within the server-run PHP code for the same page; my idea is to update a session variable on the server with the value I need to pass.

 

From the time that the variable is created by the JavaScript and the time that I need to access the variable using PHP, I cannot perform any page refresh; the JavaScript which creates the variable and the PHP that needs to subsequently use that variable are both part of the same page.

 

Any suggestions will be gratefully received.

 

 

Cheers,

Paul

Link to comment
Share on other sites

Hi Jackpf and theonlydrayk,

 

Thank you very much for your replies.

 

Jackpf, I had thought about using cookies, but the code in question is a component of a shopping cart, and we wanted to try and avoid using cookies if possible to accommodate those users who might have them disabled (the value I need to pass is essential for the correct calculation of the visitors delivery charges).

 

It may be that I am forced to go down that road if another solution cannot be found; I would just have to ensure that the cart's functionality degrades gracefully when a browser with cookies disabled is encountered.

 

theonlydrayk; I will take a good look at the page you provided an URL to, and see if I can apply the ideas presented there to the task I am facing.  I think the biggest issue I am having at the moment is just getting my head around the way AJAX calls are processed; I'm sure I'll get there in the end.

 

I will let you both know which option I ran with, and how I got on later today; thanks both again for your replies.

 

 

Cheers,

Paul

Link to comment
Share on other sites

Hi again,

 

I decided to try setting a session var first, using a modified version of the code that was suggested by theonlydrayk.

 

I can get the code called by the AJAX function to update a session var, but it would seem that the new session var value only becomes available to the PHP code (in index.php) after a page reload.

 

Here is the code I am using (the 'ajaxrequest.js' file used for this has the same content as the file I was directed to by theonlydrayk)

 

FILE: index.php

<?php session_start(); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" />
<script type="text/javascript" language="javascript" src="ajaxrequest.js"></script>
<title>AJAX Test</title>
</head>

<body>
<script type="text/javascript" language="javascript">
MyAjaxRequest('main','updatesessionvar.php?tempdistance=255');
</script>
<!-- we are not using this next output div -->
<div id="main" style="display:none;"></div>
<!-- display the session var passed from JavaScript -->
<p>DISTANCE: <?php echo $_SESSION['tempdistance']; ?></p>
</body>
</html>

 

FILE: updatesessionvar.php (this is my modified 'hello.php')

<?php session_start(); ?>

<?php
header("Content-Type: text/html; charset=ISO-8859-15");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");


// do we have a "tempdistance" session var to update?
if(!empty($_GET['tempdistance'])) {
  // update the "tempdistance" session var with passed value
  $_SESSION['tempdistance'] = $_GET['tempdistance'];
}
?>

 

I understand why I am not seeing the updated var; the PHP is being processed by the server prior to the JavaScript running in the clients browser; so back to my original question: is it actually possible to pass my JavaScript variable for use in my PHP code without a page reload?

 

Cheers,

Paul

Link to comment
Share on other sites

is it actually possible to pass my JavaScript variable for use in my PHP code without a page reload?

 

I'm a bit confused. It work no ? You successfully sent some data from a javascript code to a php script and put it in a session without reloading the page.

 

You want some data back to the javascript and change some part of the page without a complete reload ?

 

You have to output something with your hello.php that will be put in the div named 'main' like that :

 

<?php
session_start();
header("Content-Type: text/html; charset=ISO-8859-15");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

// do we have a "tempdistance" session var to update?
if(!empty($_GET['tempdistance'])) {
  // update the "tempdistance" session var with passed value
  $_SESSION['tempdistance'] = $_GET['tempdistance'];
}

echo "<b>it works</b>";

?>

 

The <div id=main></div> will be remplace by AJAX with <div id=main><b>it works</b></div>.

 

In AJAX you have 1 php script (or a html) that load first, then javascript sent data to another php script that sent the content of a div instead of a full page, so you can update partially the page.

 

I hope it was what you are looking for.

Link to comment
Share on other sites

Hi theonlydrayk,

 

I think I was a little optimistic when I thought that I could solve this problem with AJAX, in fact I have come to the realisation now that it isn't possible to do what I want at all.

 

It doesn't matter how I pass the variable to the server; be it using a session or cookies, or some other method, the PHP code which I intended would access said variable, has already been run.

 

The PHP code which needs the session variable assignment appears later in the same .php file as the JavaScript which initiates the session variable update, and remember, no page refreshes allowed.

 

So, the code I wrote following your suggestion does indeed update the session variable, as required; but unfortunately, that doesn't solved my problem, as it stands at the moment.

 

However, I do intend to use the technique I have learnt here to pass the variable to the server; I am just going to have to rework the page that it is to be included on, so that I can use a page refresh (and bearing that in mind, it will be much simpler just to pass the value on a query string url, and forget the AJAX altogether).

 

Cheers,

Paul

Link to comment
Share on other sites

Im new to ajax myself, but fort id make a suggestion if it helps.

From what I gather you have a variable set in a session, and you have a php script that uses that variable to do stuff. Then you want to update this variable on the fly with ajax, and then re-perform the php code again and update the response?

 

If that is the case, can you not also include that php code that does the thing with the session inside the same php file that deals with your ajax request, and then output the new values with ajax again?

 

Just a quick rough demo of processes:

 

1: php page is loaded, and does stuff with the already set variable.

2: You update this variable with ajax and can output this.

3: Instead of just updating and passing the session straight away, have the same php code in step 1, run through this new session value then send the response.

 

I understand this probably isnt what u mean but its worth a shot.

 

 

Link to comment
Share on other sites

Hi Fry,

 

Thanks for joining the party, and for your suggestion!!!  The session variable was to be used as a potential solution to the problem of passing a variable from the JavaScript on a page to some PHP code on the very same page.  I have now realised that no matter how I pass the variable, the PHP on the same page will never get to see the updated value I have set, as the PHP has already been processed server side.

 

If I had thought about this more before I start believing that AJAX might provide me with a holy grail solution to this issue, I would have realised that it was never going to work.

 

Cheers,

Paul

 

 

Link to comment
Share on other sites

  • 1 year later...

I needed this same solution (wanted to get screen width after user login) and this is what I did:

 

 

After the login screen user gets redirected to e.g. setwidth.php and at the begging of the code is

 

<SCRIPT LANGUAGE="JavaScript">

 

c_start = document.cookie.indexOf("width" + "=");

 

if (c_start == -1)

{

var today = new Date();

var expire = new Date();

var nDays = 0;

if (nDays==null || nDays==0) nDays=1;

expire.setTime(today.getTime() + 3600000*24*nDays);

document.cookie = "width"+"="+escape(screen.width)

+ ";expires="+expire.toGMTString();

}

 

c_start2 = document.cookie.indexOf("red" + "=");

 

if ( c_start2 == -1 )

{

var today2 = new Date();

var expire2 = new Date();

var nDays2 = 0;

if (nDays2==null || nDays2==0) nDays2=1;

expire2.setTime(today2.getTime() + 3600000*24*nDays);

document.cookie = "red"+"="+escape(screen.width)

+ ";expires="+expire2.toGMTString();

javascript:location.reload(true);

//alert("redirect");

}

 

</SCRIPT>

 

after that comes PHP part that includes redirection to main page, but before redirection code has to be

 

if ( $_COOKIE["width"] )

 

So this file is really small and those redirections doesen`t take much time.

 

 

Some may say that this is ugly solution, but give me something better...

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.