How to use a variable from $.get()
<p>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() </p>

<pre><code>$('#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 &amp;&amp; insname!='') {

        $.get('data1.php',

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

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

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

<p>Thanks</p>
