t0mmyt
t0mmyt

Reputation: 513

returned array is undefined, not async

For some reason my function is returning undefined while seemingly working in itself.

function getDomains() {
    $.ajax({
        url:    '/rewrites/cgi-bin/ajax.pl?action=listdomains',
        dataType:'json',
        async:  false,
        success: function( data ) {
            if (data.error) {
                alert(data.error);
            }
            else {
                alert(data.domains);
                return(data.domains);
            }
       }
   });
}

alert(getDomains());

My first alert shows a populated list but the second is undefined. Does this make any sense?

Upvotes: 1

Views: 86

Answers (2)

TecHunter
TecHunter

Reputation: 6141

Why don't you just do this, assuming you need your return for a function called whateverFunc():

function getDomains() {
    $.ajax({
        url:    '/rewrites/cgi-bin/ajax.pl?action=listdomains',
        dataType:'json',
        async:  false,
        success: function( data ) {
            if (data.error) {
                alert(data.error);
            }
            else {
                whateverFunc(data.domains);
            }
       }
   });
}


function whateverFunc(domains){
    alert(domains);
}

You can't return anything from success callback, it makes no sense. I would like also to complain about the async:false here. Why do you need it absolutely? You should let the call be async and manage the blocked state by yourself with some mutex or something around. In fact, you should trigger popup or whatever you need to do after you get the answer in the whateverFunc(). It's clean and you keep control on the blocking state.

Upvotes: 1

JustinMichaels
JustinMichaels

Reputation: 1092

You're in a function for the success call. That's why you're not getting a result from your getDomains function. Assign it to a variable and return the variable after the ajax call.

function getDomains() {
    var results;
    $.ajax({
        url:    '/rewrites/cgi-bin/ajax.pl?action=listdomains',
        dataType:'json',
        async:  false,
        success: function( data ) {
            if (data.error) {
                alert(data.error);
            }
            else {
                alert(data.domains);
                results = data.domains;
            }
       }
   });
   return results;
}

alert(getDomains());

Upvotes: 2

Related Questions