0

that's my part of the code:

$("#edit-field-order-borispol-und").change(foo);        
function foo() {
var result;
var customerid = $( "#edit-field-order-customer-und" ).val();
    $.ajax({
        type: 'GET',
        url: '/ops',
        data: {'customerid': customerid},
        success: function(response) {
            result = response.borispol;
            alert(response.borispol);// this alerts the info that i NEED...
        }
    });
return result;
}
foo(function(result) {
    alert(result+' it works'); // cant make it to work...
    // code that depends on 'result'
});

I have checked this: How do I return the response from an asynchronous call?

and still... I cant figure out what is wrong. Please help i'm totaly new to jquery...

Community
  • 1
  • 1

2 Answers2

0

If you want that your current code start to work, then try to add property async:false to $.ajax. and instead

foo(function(result) {
    alert(result+' it works'); // cant make it to work...
    // code that depends on 'result'
});

should be something like

function other_func(result) {
    alert(result+' it works');
    // code that depends on 'result'
};

But as it had been shown in article that you linked - this is bad way.

You'd better place your code that depends from result into success callback or like that

function foo() {
    var customerid = $( "#edit-field-order-customer-und" ).val();
    return $.ajax({
            type: 'GET',
            url: '/ops',
            data: {'customerid': customerid},
    });

}.done(function(response) {
    alert(response.borispol+' it works'); 
    //code that depends from  result (response.borispol) or anything else
});

But! Notice that code in done executes asynchronous!

kernel72
  • 89
  • 6
0

Expending on @Raj's comment

Ajax is asynchronous. Meaning by the time your function at the bottom runs you're not yet finished making the call. Import or call your "code that needs result" into the success function.

$("#edit-field-order-borispol-und").change(function () {
    $.ajax({
        type: 'GET',
        url: '/ops',
        data: {
            'customerid': $(this).val()
        },
        success: function (response) {
            var result = response.borispol;
            alert(result + ' it works'); // cant make it to work..
            // insert code that depends on 'result'
            // either by copy/paste
            // or calling it:
            codeThatNeedsResult(result);
        }
    });
});

You could also check out $.ajax documentation and think about using deferreds.

TomFuertes
  • 7,150
  • 5
  • 35
  • 49