How to pick up a variable within a javascript callback

Asked

Viewed 501 times

2

I can’t pass the variable x that is in return for another function.

I declared the global variable, but it still doesn’t work.

function pegaid() {

    var x = "";

    _agile.get_contact("[email protected]", {

       success: function (data) {
          var x= data.id;
          alert(x);
       },
       error: function (data) {
          console.log("error");
       }
    });

    alert(x);

};

1 answer

1

When you first declare the variable with var and then redeclare it within the function success: likewise var x = data.id, it gets local scope within the function of the success:.

The correct thing would be to just change the value within success:, and not redeclarate with var. When redeclaring the x in the success:, the previous line var x = ""; it’s as if it never existed. The right thing would be:

function pegaid() {

    var x = "";

    _agile.get_contact("[email protected]", {

       success: function (data) {
          x= data.id;
          alert(x);
       },
       error: function (data) {
          console.log("error");
       }
    });

    alert(x);

};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.