0

I have this:

var myapp;
function Menu($scope){

    $.ajax({
          url: "/user.php",
          type: "POST",
          
          success: function(data){
              
          }
        });
        
}

How do I use the data out of the function scope?

2
  • who calls the Menu function. Your code or some framework? Commented May 2, 2012 at 3:36
  • framework calls that function Commented May 2, 2012 at 4:55

3 Answers 3

2

You're having trouble because the ajax operation is asynchronous. This means that, after $.ajax is called, you can't control when exactly the response will arrive. In the mean time, your code keeps running normally, and if you try to use the response before it arrives, it will be empty.

You say in the comments that a framework calls your Menu function, so I'm assuming you can't control what parameters are passed to it. In this case, you should only use the data inside the success callback:

function Menu($scope){
    $.ajax({
        url: "/user.php",
        type: "POST",
        success: function(data){
            // USE data HERE
        }
    });
}

In case you can modify how Menu is called, you can pass a callback function to it, and let that manipulate the results:

function Menu($scope, ajaxCallback){
    $.ajax({
        url: "/user.php",
        type: "POST",
        success: ajaxCallback
    });
} 
// Define the callback where you will use the data
function processData(data) {
    // USE data HERE
}
// Call Menu passing the callback
Menu(whateverScopeIs, processData);
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a variable at the scope you need, and save the data to that variable. Or you can call a function and pass that data to it. For example:

function alertData(data){
  alert(data); // I can use the data here now!
}

var foo;
    $.ajax({
          url: "/user.php",
          type: "POST",

          success: function(data){
           alertData(data);
          }
        });

}

3 Comments

alert will be null as the success would not have been executed as it is async.
I'm sorry, I'm not sure I follow.
I thought alertData was to be passed as param, but I see you have used it as a method.
0

Create a global variable, assign data to it, and then use the global variable.

e.g.

var foo;
function bar(baz) {
    foo = baz;
}

bar("test");
alert(foo);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.