2

Possible Duplicate:
jQuery: Return data after ajax call success

first of all I'm not very experienced with JS or jQuery, but as far as my programming skills go I can't seem to find anything that's wrong with my approach.

var subtree;

$.post("addTreeServlet",
    {
        term:clickedNode,
        max:maxId,
        id:clickedId
    },
    function(jsonResponse){

        subtree = eval('(' + jsonResponse + ')');

    }
);

$jit.json.prune(subtree, level);
return {
     'id': nodeId,
     'children': subtree.children
};

I went through the code with the debugger, and here is what happens: The program comes back from the addTreeServlet and transmits a String representing JSON data. the eval() function takes this String and transforms it into an JSON Object (again, it looks perfectly fine in the debugger). But as soon as I leave the function(jsonResponse) the var subtree is shown as undefined, and I can't figure out why.

Is that because of the jQuery method? I have no idea...

It is also the same behavior if I just put subtree = "whatever". It becomes undefined as soon as I exit the function..

Community
  • 1
  • 1
PogoMips
  • 3,497
  • 8
  • 27
  • 34
  • 7
    It isn't THAT strange, it's a result of trying to get synchronous results with asynchronous code. you can't access `subtree` outside of the `$.post` callback function. The logic behind this function will need to be re-done in a way that doesn't require it to return data. – Kevin B Feb 01 '13 at 15:30
  • 4
    Don't use `eval` jQuery will parse JSON for you securely. – zzzzBov Feb 01 '13 at 15:32
  • 2
    Because the code "after" your `function(jsonRepsonse)` is executed **before** the function where you set `subtree`. That is a callback from asynchronous code. It isn't necessarily top-down in javascript. – Chad Feb 01 '13 at 15:33
  • 1
    Umm... What's the canonical duplicate for this one? – John Dvorak Feb 01 '13 at 15:34
  • okay, so it's basic Javascripts skills I'm missing. any ideas on how to solve this problem? – PogoMips Feb 01 '13 at 15:35
  • 1
    `function(jsonResponse){` is a callback function, see: http://stackoverflow.com/questions/4709035/understanding-jquery-callbacks – Christophe Roussy Feb 01 '13 at 15:36
  • The point is that you cannot return a result that you don't already have, and you cannot wait for it either, but you can call a function argument ("callback") anytime. – John Dvorak Feb 01 '13 at 15:37
  • The problem is that you don't have the result of the async call yet. using ajax you can pass variables to the callback, and in the call back you use subtree, then you can do something with the json data. example ajax http://weboutofthebox.com/en-GB/28/Article/AjaxparametroInvokedata – DadViegas Feb 01 '13 at 15:46

2 Answers2

1

It's waiting for post response, but your fallowing script immediately parsed by browser. So you need to do what you want to do with ajax response after post response received.

function(jsonResponse){
    var subtree = eval('(' + jsonResponse + ')');
    doSomthingWithResponse(subtree);
}
  • yep, thx, my question is answered now. I just put the callback to synchronous. That works for my case, cause the animation between sending/receiving and displaying the data is comparatively long. – PogoMips Feb 01 '13 at 16:28
0

The problem is $.post does the job for you asynchronously whereas the code beneath the $.post get executed before the return of the call... you use $.ajax with a synchronous call instead

 var subtree;
        $.ajax({
            type: 'POST',
            url: "addTreeServlet",
            data: {
                term: clickedNode,
                max: maxId,
                id: clickedId
            },
            success: function (jsonResponse) {

                subtree = eval('(' + jsonResponse + ')');

            },
            async: false
        });

        $jit.json.prune(subtree, level);
        return {
             'id': nodeId,
             'children': subtree.children
        };
pranag
  • 5,432
  • 2
  • 17
  • 15