3

I'm trying to return from the Ajax output, two variables in array, to use in another separate functions in another places:

But can't figure out How to pass it out to the new functions?

My attempt here:

var ip,country;

function getVisitorData(callback) {
    $.ajax({
        type: "GET",
        url: "http://freegeoip.net/json/",
        dataType: "json",
        async: true,
        success: function (response) {
            ip = response.ip;
            country = response.country_code;
            callback(response);
        },
        error: function (response) {
            alert("IP thing didn't work.");
        }
    });
}

function callback(response) {
    return [ip, country];
    //alert(ip + country); /* <- it works here */
}

getVisitorData(callback);

jQuery(document).ready(function () {
    var data = getVisitorData(callback);
    var ip = data[0];
    var country = data[1];
    alert(ip + country);
});

Update:

I want to use the output as GLOBAL VARIABLES !

So, get/use it just like that:

jQuery(document).ready(function () {
    alert(ip)
});

Sorry if I wasn't clear enough about that!

Many thanks in advance!

Homer
  • 355
  • 1
  • 5
  • 17
  • 1
    possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – doldt Jul 18 '15 at 18:23
  • possible duplicate of [Can't parse and return ajax string to jquery variable](http://stackoverflow.com/questions/31360437/cant-parse-and-return-ajax-string-to-jquery-variable) – vinayakj Jul 18 '15 at 18:29
  • 1
    Regarding your update, you're very much on the wrong track here, sorry! Asynchronous JavaScript simply doesn't work that way. Listen to the people who are telling you that you that you need to *call* a function with the returned data instead of just storing it in a global variable, and heed their advice. That is the only way you will succeed in solving the problem. You can use a callback, or you can use a promise - those are simply two ways of doing the same thing. What you *can't* do is just store the data in a global variable and expect it to be available after you issue the ajax request. – Michael Geary Jul 19 '15 at 05:14
  • 1
    I updated one of your fiddles to turn it into a working example: http://jsfiddle.net/mea2nr7t/1/ – Michael Geary Jul 19 '15 at 05:23
  • Thanks @MichaelGeary, Okay. If the callback is a necessary step to get the data out, it's okay, lets call it. But how can I pass/return these data from the **CALLBACK function** then? this is my purpose, cuz I want to use this data later as variables. that's it. – Homer Jul 19 '15 at 05:32
  • Someplace you have some code that wants to use the data provided by the ajax call. So make that code into a function with parameters, and call that function from your callback, as I did in the working example. Think of the `alert()` in that code as your other function. The `alert()` works fine, because it called directly from the callback, and the data is passed into it as parameters. Do the same thing with whatever code you have that wants to use the data, and it will work too. – Michael Geary Jul 19 '15 at 05:39
  • 2
    What you can't do is "return" the data or leave it behind in a global variable or the like. Here's the problem with that: How will your code that needs the data know when it has actually been received from the server? The only way to know that the data is ready is when the callback has been called. – Michael Geary Jul 19 '15 at 05:40
  • As @MichaelGeary says, use a function with parameters to be called as callback or from callback, else you have only other option to make your AJAX call synchronous and if you are ok with that go for it,but of course its not recommended as is totally opposite of AJAX's purpose. – vinayakj Jul 19 '15 at 08:05

5 Answers5

4

I would tend to favor a promise here:

var ip = {};
var country = {};
var getstuff = {};

function callback(response) {
    ip = response.ip;
    country = response.country_code;
  // not really needed  return [ip, country];
}

function getVisitorData() {
    getstuff = $.ajax({
        type: "GET",
        url: "http://freegeoip.net/json/",
        dataType: "json",
        async: true
    }).done(callback)
    .fail(function (response) {
        alert("IP thing didn't work.");
    });
}
jQuery(document).ready(function () {
    getVisitorData();
    getstuff.done(function () {
        alert(ip + country);
    });
});

Here it is in action: http://jsfiddle.net/MarkSchultheiss/7bmnsvay/

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • Thanks @Mark Schultheiss ! and sorry if I wasn't clear in my question! I've updated it. Just want to use the output as GLOBAL VARIABLES ! – Homer Jul 19 '15 at 05:04
  • That should work then `var ip = {}; var country = {};` – Mark Schultheiss Jul 19 '15 at 14:13
  • 1
    Note when you do: `jQuery(document).ready(function () { var data = getVisitorData(callback); var ip = data[0]; var country = data[1]; alert(ip + country); });` you define NEW variables – Mark Schultheiss Jul 19 '15 at 14:16
2
function getVisitorData(callback) {
    $.ajax({
        type: "GET",
        url: "http://freegeoip.net/json/",
        dataType: "json",
        async: true,
        success: function (response) {
            ip = response.ip;
            country = response.country_code;
            callback(response);
        },
        error: function (response) {
            alert("IP thing didn't work.");
        }
    });
}
function callback(data) {
    var ip = data[0];
    var country = data[1];
    return [ip, country];
}

jQuery(document).ready(function () {
    getVisitorData(callback);
});

Do the data manipulation in callback function not in any other function. For more info visit Callback function

Community
  • 1
  • 1
vinayakj
  • 5,591
  • 3
  • 28
  • 48
  • Thanks @vinayakj , but I still don't know how to use the output after that. I want to use `ip` and `country` alone, as global variables, just like that: `jQuery(document).ready(function(){ alert(ip) });` – Homer Jul 19 '15 at 04:13
  • So if I wasn't clear enough about that, I've updated the question! – Homer Jul 19 '15 at 04:23
0

Create a global object.

Var objMyData={};

Store ip and country code in that object.

objMyData.IP= response.IP; objMyData.Country= response.country_code;

Now pass objMyData object as a parameter to any function.

Saravana
  • 1
  • 2
  • Thanks @Saravana ! This] is my attempt (http://jsfiddle.net/uL5jnukd/), would you please check it and let me know what the error is?. please excuse the I'm newbie! Thank you! – Homer Jul 19 '15 at 04:50
  • This is the common problem lot of us are not knowing is, before your service call success or failure, the line next to your service call will execute, So you need to set some timeout //Create a global object. var objMyData = {}; jQuery(document).ready(function () { //Now pass objMyData object as a parameter to any function. getVisitorData(objMyData); setTimeout(function(){ console.log(objMyData); }, 500); }); – Saravana Aug 02 '15 at 05:02
0

I do not know why you need to return an array in your callback.As ajax is asynchronous, it will not wait till the response comes, it will execute the rest of the statements. So return value will give you undefined. You can use/assign the response only after response comes.

function getVisitorData(callback) {
    return $.ajax({
        type: "GET",
        url: "http://freegeoip.net/json/",
        dataType: "json",
        async: true

    });
}

jQuery(document).ready(function () {

    $.when(getVisitorData())
    .done(function(respone) {
      var ip = response.ip;
      var country = response.country_code;
      //here you can trigger a custom event with the values, wherever you need, just bind the event and use the data.
       $(document).trigger("responseDataPublished", [ip, country]);
    })
    .fail(function(response){
       alert("IP thing didn't work.");
    });
});
jrath
  • 980
  • 4
  • 14
  • Thanks @jrath ! and sorry if I wasn't clear in my question! I've updated it. Just want to use the output as GLOBAL VARIABLES ! – Homer Jul 19 '15 at 05:15
0

This is the common problem lot of us are not knowing is, before your service call success or failure, the line next to your service call will execute, So you need to set some timeout

//Create a global object. var objMyData = {}global object;

function getVisitorData() {function call $.ajax({`ajax type: "GET", url: "http://freegeoip.net/json/", dataType: "json", async: true, success: function (response) { //Store ip and country code in that object. objMyData.ip = response.ip; objMyData.Country = response.country_code; }, error: function (response) { alert("IP thing didn't work."); } }); }

jQuery(document).ready(function () { //Now pass objMyData object as a parameter to any function. getVisitorData();method call setTimeout(function(){ console.log(objMyData); }, 500); });

Saravana
  • 1
  • 2