0
$.ajax({
  type: 'POST',
  url: 'xxxx.com/init',
  ContentType: 'application/json',
  dataType: 'json',
  data: data,
  success: function(resp) {
    $.cookie("tc", resp.tokenCode); 
  }
});

console.log($.cookie("tc"));

I try to create a cookie inside success, but it doesnt seem working. it logs undefined...

m59
  • 43,214
  • 14
  • 119
  • 136
  • 1
    Ajax is async. The call hasn't completed and the success callback hasn't executed, and therefore the value hasn't been set when the `console.log()` line executes. See [How to return the response from an ajax call](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call). – Jason P Dec 18 '13 at 00:22
  • By the way, it's helpful to the community and to those that post answers if you will select a best answer if your question in answered. Click the check mark on the answer. Thanks and welcome to Stack Overflow! – m59 Dec 18 '13 at 00:31

3 Answers3

1

That's because ajax calls are an asynchronous operation. Functions that can see the cookie will need to be set as callbacks or accessed on page-reload (if the cookie is still around).

$.ajax({
  type: 'POST',
  url: 'xxxx.com/init',
  ContentType: 'application/json',
  dataType: 'json',
  data: data,
  success: function(resp) {
    $.cookie("tc", resp.tokenCode);
    myFunction();
  }
});

function myFunction() { 
  console.log($.cookie("tc"));
}

As you are also having issues with $.cookie, you could use localStorage or sessionStorage like this:

localStorage.tc = resp.tokenCode;
console.log(localStorage.tc);
m59
  • 43,214
  • 14
  • 119
  • 136
1

Your console.log is running before your ajax call completes in what is known as a race condition. The browser gets to the console.log before the ajax call can complete, so your cookie has not yet been set as the success callback function has not been called yet. Trying placing that logging statement inside your callback:

success: function(resp) {
  $.cookie("tc", resp.tokenCode);
  console.log($.cookie("tc")); 
}
Michal
  • 2,532
  • 1
  • 19
  • 27
  • it still logs undefined – user3095297 Dec 18 '13 at 00:24
  • 2
    @user3095297 basic debugging - log `resp.tokenCode` I bet that is empty, so you're giving your cookie an empty value. – m59 Dec 18 '13 at 00:25
  • @m59 wooooow you are a genius, but apparently thats not the problem. i found out that it doesn't work because chrome ignores local jquery cookies. – user3095297 Dec 18 '13 at 00:30
  • Ouch, nice find. You can start Chrome with the `--enable-file-cookies` flag for that. But you will still need to keep the `console.log` inside your success statement. – Michal Dec 18 '13 at 00:32
0

The console.log is running before the success callback. Put the log inside the callback and see what happens.

tzerb
  • 1,433
  • 1
  • 16
  • 35