0

Is there a way to set a session variable from withing my JS function?

I have the following JS code:

$.ajax({
    url: "ajax.php",
    type: "POST",
    data: { 
        tid: '.$testID.',
        do:"'.$do.'"
    },
    success: function( html ) {
        $("#partBox").html( html ); 
        // add PHP here?            
    }
});

I would like to set the following var in the session, on SUCCESS:

$_SESSION['hgt'] = 'Math.ceil($("#partBox").height() / 2)';

I have no idea if this is even possible... Alternatively I could probably use cookies...

1 Answer 1

5

You can't set any PHP variables in JavaScript. Once the Page has finished loading PHP has done its job and is out of the picture. If you want to set a session variable using JavaScript you can do it one of two ways:

  1. Use Ajax to send the value to a PHP script to set the session variable
  2. Store it in a cookie and on the next page load have PHP use the value of that cookie to create the session varibale
Sign up to request clarification or add additional context in comments.

4 Comments

I need to capture this value into a session to use in cases where I have not received SUCCESS response. And how do I send it over again with AJAX? Do I put another ajax call withing SUCCESS section?
That would be exactly where it goes
Hmm, that sounds a bit more convoluted than I can handle. Can I set a cookie from withing SUCCESS area?
To be honest; it's a best practice to use both cookies and session variables. Some users don't allow cookies.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.