Ajax call .Net and send cookie

I am making an ajax call from an html page (mobile) to a .net server for login and authentication. Now I am sending a JSON response with success: true. All this works fine, but I need to set cookies so that the user is remembered when I make other calls to record data after logging in.

I read about using JSONP, but I would prefer not to go this route unless I need it, as that means a lot of change. I would just like to send the cookie back in response and set it manually on the client side.

How to get this cookie (or create a cookie?) On the server side in .net and send it back in response?

+2
source share
2 answers

In your successajax event you can set a cookie on the client side

Assuming your JSONlooks like this

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

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

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

The SetCookie function sets a 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;
}
+3
source

You can configure the client side of the cookie using javascript after discovering your success: the true answer.

+1
source

All Articles