2

I am making an ajax call from an html page (mobile) to a .net server for a login and authentication. Right now i am sending back a JSON response with success:true. This all works fine but I need to set the cookies so that the user is remembered when I make other calls to record data once logged in.

I read about using JSONP, but I would rather not go that route if I don't have to since it means changing a lot. I would like to just send the cookie back in the response and set it manually on the client side.

How do I retrieve this cookie (or create the cookie?" on the server side in .net and send it back in the response?

pfunc
  • 1,305
  • 2
  • 24
  • 52

2 Answers2

3

In your success event of ajax, you can set the cookie in client side

Assuming your JSON is like this

  {    "success": "true",    "username": "scott"   }

And in your ajax function, check the JSON and if the success item value is true, set the cookie.

$.ajax({
        url: "someserverpage.aspx",
        success: function(data) {
           if(data.success=="true")
           {
              SetCookie("YoursiteUsername",data.username,365);                   
           }
        }
});

The SetCookie function sets the cookie.

function SetCookie(c_name,value,exdays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
  document.cookie=c_name + "=" + c_value;
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Ok, I tried this, but when I make subsequent calls to other functions to record data (that require user authentication), the user is not being recognized. Is there something else that can be done? – pfunc Aug 10 '12 at 15:34
  • you gotta read the cookie value for that. This is only setting the cookie. – Shyju Aug 10 '12 at 15:36
1

You can set the cookie client-side with javascript after detecting your success:true response.

Facio Ratio
  • 3,373
  • 1
  • 16
  • 18