0

I was wondering if there is a way to set session variable in Ajax response, which would basically look like this:

// this is response
function(response)
{
<?php $_SESSION['ID'] = response.id ?>
// or something similar to this? 
}

And then afterwards when I need to use the session so that I can access it.

// (Some php file)

$var_id = $_SESSION['ID']; 

Is this doable?

8
  • JavaScript code runs on the client. It runs in somebody's web browser. It cannot do things in code on your server. Commented May 9, 2016 at 13:42
  • you can do on your server side, using PHP in your scenario Commented May 9, 2016 at 13:43
  • You could take that response.id and send it in an ajax call to a php endpoint which sets it Commented May 9, 2016 at 13:43
  • I understand but the value that I need to store into the session should be just done locally on someones web browser, and then later on retrieved in code.. I think its very logical thing that I mentioned, there has to be a way to do this... Perhaps if not storing the value into the session, is there some other way? Commented May 9, 2016 at 13:44
  • you could use a cookie instead Commented May 9, 2016 at 13:44

2 Answers 2

1

Here are three functions to set, get, and delete cookies

https://jsfiddle.net/stevenkaspar/gnoj9aop/

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
        }
    }
    return "";
}
function deleteCookie(cname){
  document.cookie = cname+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use HTML5 sessionStorage Object to save the data locally but for a single session . The data is deleted when the user closes the specific browser tab.

sessionStorage.id = response.id ;

1 Comment

And how do I access the sessionStorage from the php file ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.