Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can JavaScript read HTTP Session object?

Is it possible to read the value of a dynamic variable like httpRequest.getSession("attr_name") from within a JavaScript?

like image 730
fmjaguar3 Avatar asked Mar 19 '12 13:03

fmjaguar3


2 Answers

(With Javascript, I assume that you mean client script in the browser.)

No, that is not possible. The contents of the Session object never leaves the server, so client script can't read Session data directly.

If you want to access it in the browser, you have to read the data out of the Session object and send it along in the response (for example in a hidden field), or provide a web service that reads data from the Session object and returns to the browser.

like image 117
Guffa Avatar answered Oct 02 '22 06:10

Guffa


As I said in my comment, the only way would be some kind of Ajax call and request it from the server. I dont know what backend your using, here's how I would do it in Asp.net MVC and jQuery.

(If there are minor syntax errors, I apologize - not in front of a compiler)

public class HomeController : Controller
{

    //abstract the session code away, don't let the evil javascript touch
    //it directly. Ideally this would all be in a seperate logic class or something.
    public string NameAttribute
    {
       get
       {
           return Session["attr_name"] as string ?? string.empty;
       }
    }
    [HttpGet]
    public string GetNameAttribute()
    {
        return NameAttribute;
    }
    public ActionResult Index()
    {
        return View();
    }
}



<script>
$(function(){
    $.get( 'home/GetNameAttribute', function( response ) {
        var name = response; //don't forget error checking, ommited
    });
});
</script>

Alternatively, you could always write down the values you need into hidden fields, and read them with normal javascript.

like image 38
asawyer Avatar answered Oct 02 '22 05:10

asawyer