Reputation: 61
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');
}
})
})
Upvotes: 6
Views: 5795
Reputation: 487
You can include this small javascript library (~800 bytes gzipped!). https://github.com/js-cookie/js-cookie It used to be a jquery plugin but it had very few dependencies on jquery so they made it its own stand alone library.
Read cookie:
<script src="/path/to/js.cookie.js"></script>
Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined
Upvotes: 1
Reputation: 686
If you don't want to use document.cookie , you can use cookie js which will help to get value of any key Please get js from https://github.com/js-cookie/js-cookie and see it's usage.
Upvotes: 0
Reputation: 4202
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 "";
}
Upvotes: 3