Gustavo Martins
Gustavo Martins

Reputation: 23

I need to use a var outside of a get function in jQuery

Consider this code snippet:

$('#selectone').change(function(){
    var amount;
    $.get('search.php', {search:'units'}, function(result){
        //this will return only one or zero for me.
        amount = result;
    })
    if(amount>0)
    {
        alert('This option has been selected, please select another one');
    }
})

My variable amount are coming always undefined. How can this be fixed or refactored?

Upvotes: 2

Views: 70

Answers (2)

Jasper
Jasper

Reputation: 75993

That is because the following code is running before the callback function in your $.get() request:

if(amount>0)
{
    alert('This option has been selected, please select another one');
}

AJAX calls are asynchronous, meaning that the code around them runs as the AJAX call awaits the response. So the if(amount>0) code is running before the AJAX callback fires (meaning that for your if/then statement amount will always equal null).

To do what you want I suggest putting that code inside the callback function for your $.get() request:

$('#selectone').change(function(){
    $.get('search.php', {search:'units'}, function(result){
        //this will return only one or zero for me.
        if(result>0)
        {
            alert('This option has been selected, please select another one');
        }
    });
});

--Update--

You can also make use of jQuery's $.when() method:

$('#selectone').change(function(){
    var amount;
    var jqXHR = $.get('search.php', {search:'units'}, function(result){
        //this will return only one or zero for me.
        amount = result;
    });
    $.when(jqXHR).then(function () {
        if(amount>0)
        {
            alert('This option has been selected, please select another one');
        }
    });
});

Upvotes: 7

Niels
Niels

Reputation: 49919

You can't just use it inside the success function? Would be the best way:

$('#selectone').change(function(){
 var amount;
    $.post({
        async : false, // this makes it possible
        url: 'search.php', 
        data: {search:'units'}, 
        success : function(result){
            //this will return only one or zero for me.
            amount = result;
        }
    });

    if(amount>0)
    {
        alert('This option has been selected, please select another one');
    }
})

Upvotes: 0

Related Questions