Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get server side cookies value in javascript?

Tags:

javascript

c#

How to get server side cookies value from JavaScript. Here I have declare cookies from server side

I want to check whether cookies are null or not.

The C# code:

String UserId = usrDT.Rows[0]["user_id"].ToString();
UserDAO.StorageCookies.myCookie = new HttpCookie("myCookie");
UserDAO.StorageCookies.myCookie.Values.Add("userid", UserId);
UserDAO.StorageCookies.myCookie.Expires = DateTime.Now.AddHours(5);
HttpContext.Current.Response.Cookies.Add(UserDAO.StorageCookies.myCookie);

The JavaScript Code

$(document).ready(function () {
    $(".edit-btn").click(function () {
        var cookies = '@HttpContext.Current.Request.Cookies["myCookie"].Value';
        alert(cookies);
        var v = $(this).data("textval");
        var qid = $(this).data("ques-qid");
        var getResponce = "http://localhost:1234/Models/answer.aspx?q=" + qid;
     if (cookies != "") {
        $.ajax({
            type: "GET",
            url: getResponce,
            data: {
                "Submit": "EditAnswer",
                "ans_id":v
            },
            success: function (msg) {
                var htmlEditor = $find("editAnswer_ctl02");
                htmlEditor.set_content(msg);
            }
        })
     } else {
         alert("elseCondition");
            $('.login-form').modal('show');
        }

    })
})
like image 299
Kamar Rahi Avatar asked Sep 26 '22 21:09

Kamar Rahi


1 Answers

Your JavaScript is able to select cookies as cookies stored at clients browser, just use this function

function getCookie(cname) {
   var name = cname + "=";
   var ca = document.cookie.split(';');

   for(var i=0; i<ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1);
      if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
   }

   return "";
} 
like image 173
Armen Avatar answered Oct 11 '22 14:10

Armen