1

My code is like this and I'm trying to fill a form field with the result of the jQuery function. But it's not working. What am I doing wrong here? It logs the result to the console fine, including the hash and the array:

jQuery(document).ready(function() {
    new GetBrowserVersion().get(function(result, components){
        console.log(result); //a hash
        console.log(components); //an array
    });

    var unique_id = result;

    $('#unique_id').val(unique_id);      
 });

What I get is this:

Uncaught ReferenceError: result is not defined

Followed by the hash and array.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
user1996496
  • 972
  • 2
  • 10
  • 24
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Sep 27 '16 at 22:03

2 Answers2

5

you are closing the function and the value is not available (in scope) to use to update the input:

jQuery(document).ready(function() {
    new GetBrowserVersion().get(function(result, components){
        console.log(result); //a hash
        console.log(components); //an array

        var unique_id = result;
        $('#unique_id').val(unique_id);
    });
});

Incidentally - you can use the argument directly in the function without creating the intermediate variable of result::

jQuery(document).ready(function() {
    new GetBrowserVersion().get(function(result, components){
        console.log(result); //a hash
        console.log(components); //an array

        $('#unique_id').val(result);
    });
});
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
gavgrif
  • 15,194
  • 2
  • 25
  • 27
1

If you actually need result elsewhere, you can use a closure to get the value outside of get().

var result;

new GetBrowserVersion().get(function(r, components){
    console.log(r); //a hash
    console.log(components); //an array

    result = r; // assigns to the result in the enclosing scope, using a closure
});

var unique_id = result;
$('#unique_id').val(unique_id);
recursive
  • 83,943
  • 34
  • 151
  • 241