pst
pst

Reputation: 11

Accessing a session in jQuery

Can I set a session variable in jQuery?

I need to store some data in the session from jQuery and I also want to retrieve that data via jQuery.

Is there anything like

$.getSession.set("var","value");

Upvotes: 1

Views: 10148

Answers (2)

jwaliszko
jwaliszko

Reputation: 17064

Session is accessible at the server side. But if you want, you can access your session by writing a function, which for example invokes ajax request to your server and gets whatever you want.

EDIT:

I'll show you this using ASP.NET MVC framework, as I like it much. For the other frameworks idea is the same - just ask server about session.

So, let it be like below at the server side - simple controller and 2 basic actions are written:

public class HomeController : Controller
{
    public ActionResult Index()
    {            
        // store sample data
        Session["user"] = new { name = "Anton Chigurh", age = 42 };
        return View();
    }

    public JsonResult GetSessionValue(string key)
    {
        return Json(Session[key]);
    }        
}

Firstly, you have to store something into the session, for example by invoking Index action. Next, invoke the GetSessionValue action to retrieve value previously stored. Unless you have disabled session for your application, or cookies in your browser, you should get correct value.

How to get the value ? Just send ajax request:

  1. You can write javascript function which will do synchronous request - which in fact can freeze your browser for some minor time (depends on your server time consumption used for some calculations, network infrastructure conditions etc.):

    function getSessionValue(key) {
        var result;
        $.ajax({
            url: "/Home/GetSessionValue",
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({ key: key }),
            contentType: 'application/json; charset=utf-8',
            async: false
        }).done(function (data) {
            result = data;
        });
        return result;
    }
    
    // invoke
    var user = getSessionValue("user");
    console.log(user.name + ": " + user.age);
    
  2. or an asynchronous version, which invokes a callback when done:

    function getSessionValue(key, callback) {    
        $.ajax({
            url: "/Home/GetSessionValue",
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({ key: key }),
            contentType: 'application/json; charset=utf-8',        
        }).done(function (data) {
            callback(data);
        });
    }
    
    // invoke 
    getSessionValue("user", function(x) {
        console.log(x.name + ": " + x.age);
    });
    

BTW: I've used json seriazlization, as it's the approach I prefer while passing the objects to and from the server. Other thing - jQuery done event will only be triggered on success. In case of some errors at the server side (ex: uncaught exception), request returns http 500 and event is not invoked.

Upvotes: 3

Ravi Y
Ravi Y

Reputation: 4376

If you are looking at handling client-side sessions with jQuery, you would need a plugin for that.

One that I can think of is jQuery Session Plugin.

Upvotes: 1

Related Questions