jquery - How to use javascript variable out of the scope? -
this question has answer here:
- how return response asynchronous call? 24 answers
i using $.get functionality json data action method. out of $.get() function javascript variable getting default value.
code like:
var data = 0; $(document).ready(function () { var url = "/controller/action"; $.get(url, null, function (data) { data = json.stringify(data); console.log(data); }); console.log(data); });
output display like:
[{"name":"jatin","address":"surat","colorscheme":"#1696d3"},{"name":"jatin","address":"surat","colorscheme":"#1696d3"},{"name":"jatin","address":"surat","colorscheme":"#1696d3"}]
and
display 0
.
how may use data value out of scope?
thanks, jatin
don't declare 'var' in front of data in $.get call. declares new variable. since data defined outside function scope, simple change value doing "data = json.stringify(data);"
var data = 0; $(document).ready(function () { var url = "/controller/action"; $.get(url, null, function (data) { data = json.stringify(data); console.log(data); }); console.log(data); });
edit: after chatting op, trying use response data $.get in synchronous manner. that, suggested either moving code relies on response data in ajax success function or use jquerys $.when() function