Wednesday, December 16, 2015

Updating a Session Variable With JavaScript

Although JavaScript is client side code with an AJAX call you can set or update a session variable on the server when client side code fires.

In my case I couldn't do a post back, since I could not have a form on the page, so I needed to do a reload.  I still needed the values from the page, which reload does not preserve.  Because it is a reload it shouldn't preserve those values, but for my purpose I needed one of them.

What I ended up doing was using JQuery to make an AJAX call to a handler page.

Once the AJAX call returns then I call the reload.  The code looks similar to this:



cache: false,

url: sURL,

datatype: "html"

}).done(function (data) {

if (data != "") alert(data);

//alert("Should reload");

window.location.href = window.location;



.fail(function (xhr, ajaxOptions, thrownError) {




sURL is the address of the handler page.  You will need to pass a parameter to the handler page to tell it that you want to call the routine in the handler that sets the session variable.  The handler code in ASP.NET with C# would look like this:

static HttpContext _context;

public void ProcessRequest(HttpContext context)


   string retval = "";

   _context = context;

   switch (context.Request["method"])


     case "SetSession":

        Session[context.Request["SessionVarName"])] = context.Request["SessionValue"])


        context.Response.ContentType = "text/plain";

        retval = "Invalid method specified";