eddy
eddy

Reputation: 13

How to use a variable from $.get()

Kindly take a look at $.get(). I need to use the variable nextId in the subsequent $.post() but having the problem of being undefined outside the scope of $.get()

$('#addbtn').click(function(){

    var insname = $('#ins').val();
    var itemexist = false;

    $.each($('#selname option'), function(key, value){
        if($(this).text() == $.trim(insname)){
            itemexist = true;
            alert("Item already exists: "+$(this).text());
        }
    });

    if(insname=='') alert("Cannot be empty");

    if(!itemexist && insname!='') {

        $.get('data1.php',

            function(retId){
                var nextId = retId;
                var incrementlength = 1;
                incrementlength+= $('#selname option').length;

                $('#selname').attr('size',incrementlength);
                $('#selname')
                    .append($('<option></option>')
                    .attr('value', nextId).text(insname));
                $('#ins').val('');
            });

        alert(nextId);//nextId is not defined
        $.post('data1_1.php', {id: nextId, name: insname},);
    }
});

Thanks

Upvotes: 0

Views: 133

Answers (2)

asleepysamurai
asleepysamurai

Reputation: 1372

What happens here is that the nextId is set during an asynchronous callback, so when you are calling the alert, nextId is undefined, because it hasn't been set yet. If you want to use the returned nextId in the $.post() you will have to call the $.post() after the $.get() callback completes. Modify your code as below and it should work:

Try this:

$('#addbtn').click(function(){

    var insname = $('#ins').val();
    var itemexist = false;

    $.each($('#selname option'), function(key, value){

        if($(this).text() == $.trim(insname)){
            itemexist = true;
            alert("Item already exists: "+$(this).text());
        }
        });

        if(insname=='') alert("Cannot be empty");
        if(!itemexist && insname!=''){
        $.get('data1.php',
                function(retId){
                    var nextId = retId;
            var incrementlength = 1;
            incrementlength+= $('#selname option').length;
            $('#selname').attr('size',incrementlength);
            $('#selname').append($('<option></option>').attr('value', nextId).text(insname));
            $('#ins').val('');
            alert(nextId);//nextId should be defined
            $.post('data1_1.php',
                    {id: nextId, name: insname},
                    );
            }
        });


});

Upvotes: 3

zerkms
zerkms

Reputation: 254886

That is because $.get is performed asynchronously (that is what A in AJAX means)

You can:

  1. Change the $.get to $.ajax and make it synchronous with async: false option
  2. (preferred) To perform all your work in $.get callback

Upvotes: 4

Related Questions