How to get a variable inside a javascript callback

2

I can not pass the variable x that is in return to another function.

I declare the global variable, but it still does not 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);

};
    
asked by anonymous 17.12.2017 / 03:53

1 answer

0

When you declare the variable the first time with var and then redeclate it inside the success: function in the same way var x = data.id , it gets local scope within the success: function.

The correct thing would be to only change the value inside success: , and not redeclarate with var . When redeclaring x in success: , the previous line var x = ""; is as if it had never existed. The correct 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);

};
    
17.12.2017 / 04:17