-2

I am using $.get functionality to get json data from action method. But out of $.get() function JavaScript variable getting default value.

code look 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 look like:

[{"Name":"Jatin","Address":"surat","colorScheme":"#1696d3"},{"Name":"Jatin","Address":"surat","colorScheme":"#1696d3"},{"Name":"Jatin","Address":"surat","colorScheme":"#1696d3"}]

And then

Display 0.

How may I use Data value out of scope?

vinS
  • 1,417
  • 5
  • 24
  • 37
Jatin Gadhiya
  • 1,955
  • 5
  • 23
  • 42

1 Answers1

3

Don't declare 'var' in front of data in the $.get call. This declares a new variable. Since data is already defined outside the function scope, simple change the value by 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 to OP, he was trying to use the response data from $.get in a synchronous manner. For that, I suggested either moving the code that relies on the response data in an ajax success function or use jquerys $.when() function

Walker Boh
  • 750
  • 6
  • 13
  • I am not getting your point can you give me updated code as per you said. – Jatin Gadhiya Apr 23 '15 at 01:13
  • Look closely, my answer does contain updated code. Instead of "var data = JSON.stringify(Data)" it's just "data = JSON.stringify(Data)" – Walker Boh Apr 23 '15 at 01:15
  • I have also try look like this. but not getting result. and i have also update my question you can see now. – Jatin Gadhiya Apr 23 '15 at 01:16
  • Why is it that you are declaring data with a value of 0? Are you expecting to see data with a value of 0 after your $.get call? – Walker Boh Apr 23 '15 at 01:21
  • I am just assigning value instead of null – Jatin Gadhiya Apr 23 '15 at 01:26
  • I have also try look like: $(document).ready(function () { var tt; var url = "/Controller/Action"; $.get(url, null, function (Data) { console.log(Data); tt = JSON.stringify(Data); $("#test").html(tt); console.log(tt); }); var data = $("#test").html(); console.log(data); }); // getting empty string – Jatin Gadhiya Apr 23 '15 at 01:29
  • Sorry, but I'm no longer sure what you are asking anymore – Walker Boh Apr 23 '15 at 01:34
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/75988/discussion-between-jatin-gadhiya-and-walker-boh). – Jatin Gadhiya Apr 23 '15 at 02:12