0

Hi I have this code ajax and i want get var respon but i cant do it in outside his function..

$.ajax(settings).done(function(response) {

respon = [];
respon[0] = response;
respon[1] = respon[0].data.translations[0].translatedText;

    });
console.log(respon); // is not defined

1 Answers1

0

That's because ajax is an asynchronous call, meaning it takes some time before response is available. In synchronous order this is what happens:

  1. $.ajax(settings) gets called
  2. console.log(response) gets called and isn't available yet => undefined
  3. response becomes available when done

You can wrap console.log() in an outer scope function and call from the done() function

$.ajax(settings).done(function(response) {
    myCallback(response);
});

function myCallback(data){
    window.respon = []; // var respon = [];
    window.respon[0] = data;
    window.respon[1] = data[0].data.translations[0].translatedText;

    console.log(window.respon);
}

Now I've made it explicit that respon is part of the window object since you didn't declare it. It's not "really" necessary but it's what happens. If you don't need it anywhere else you should declare it and keep it in scope => use var, let or const depending on what you're planning to do with it.

Tim Vermaelen
  • 6,869
  • 1
  • 25
  • 39
  • I really appreciate your help, but the same problem is because I want her outside the function – Dragon Jamey May 07 '20 at 00:44
  • Since you didn't declare `respon` outside the function it "becomes" part of the window object so it is available outside the function, just not when you want to call it. Perhaps you should fill us in on the idea why you need it outside the function and then we can help you better. – Tim Vermaelen May 07 '20 at 00:47