I've this piece of code, and i built the other function only to try another way to do that.
var cookie_val = "";
function getCookie() {
$.when($.ajax("../handlers/users/get_user.ashx")).then(function (data, textStatus, jqXHR) {
$.when(getCookieValue(data)).then(function () {
cookie_val = $.cookie("default_value:" + cookie_val);
});
});
return cookie_val;
}
function getCookieValue(data) {
cookie_val = data;
}
this works, but only if i execute the function twice, how can i do to make this work at the first call?
You have to wait for the ajax
request to finish before grabbing the value: https://api.jquery.com/jQuery.when/ . The requests made in getCookie
are both asynchronous, so they don't halt other code from executing while they are waiting for a response from the server. There's two ways you can get around this:
Return the deferred object created in getCookie
function getCookie() {
return $.when(....
}
And when it's done, do what you need with the cookie value
getCookie().done(function (cookie_value) {
console.log(cookie_value);
});
Alternatively, make the call synchronous: https://api.jquery.com/jQuery.ajax/
function getCookie() {
$.ajax({
url: '../hnadlers/users/get_user.ashx',
async: false
}).done(function (data, textStatus, jqXHR) {
cookie_value = $.cookie('default_value:' + data);
});
return getCookieValue();
}
Also, are you sure getCookieValue
shouldn't return cookie_val
, as your current implementation suggests, it should be named setCookieValue
.