i want use local variable global variable , told way create variable outside function, this:
var foo = null; function bar() { foo = 3; } console.log(foo); however foo logs null, instead of 3. simplest example think of, want able use data variable created in function throughout whole script.
what doing wrong?
same question in ajax request :
var status = null; .ajax({ url: myurl, success: function (data) { status = data.status; //returns string console.log(status); // works, string }, datatype: 'jsonp' }); console.log(status); // still null
you need call function first this.
var foo = null; function bar() { foo = 3; } bar(); console.log(foo); your best bet here call function logs data after ajax runs. in example created function called logit() called in ajax request state.
var status = null; $.ajax({ url: myurl, success: function (data) { status = data.status; //returns string console.log(status); // works, string logit(); }, datatype: 'jsonp' }); function logit(){ console.log("logit(): " + status); } the reason getting null because order code running:
- sets
statusnull - saves ajax memory run when requests completes doesn't run yet
- logs
statusstillnullbecause success callback hasn't run yet - the ajax request completes , runs success callback
statussetdata.status
Comments
Post a Comment