1

I have been trying multiple methods to get the returned data from a $.get method but am having no luck. So far, the code below returns an alert with the data I want but what I want to achieve is setting the finalPublicIp variable to the returned data so that I may use this variable in other places.

var finalPublicIp = $.get("https://api.ipify.org/", function(data){
    alert("Data: " + data);
});

Thank you for all help in advance.

1 Answers1

1

The behavior of the $.get() method is asynchronous. You have to assign the value in the callback method:

var finalPublicIp;

$.get("https://api.ipify.org/", function(data){
    finalPublicIp = data;
});

Note that due to the asynchronous behavior, the value of finalPublicIp will only be set after the callback method is executed.

Daichi
  • 198
  • 2
  • 13
  • When alerting the var now, it returns undefined? –  Aug 10 '17 at 01:02
  • @mrchriswindsor Because the asynchronous callback has not finished executing yet. You have to wrap your head around this asynchronous behavior first. – Robby Cornelissen Aug 10 '17 at 01:05
  • @RobbyCornelissen oh my bad. I understand what you are saying now. So there is no way to achieve this? –  Aug 10 '17 at 01:08
  • Yeah, you could get your AJAX method to executed synchronously, but this is not the preferred approach as it blocks the entire processing loop. See here: https://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re – Robby Cornelissen Aug 10 '17 at 01:09
  • @RobbyCornelissen I have reviewed that answer and have tried a few things. Could you be ever so kind sir and show me how I would change my method to be non-synchronous. Any more help is extremely appreciated! –  Aug 10 '17 at 02:18