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
What happens here is that the
nextIdis set during an asynchronous callback, so when you are calling the alert,nextIdis undefined, because it hasn’t been set yet. If you want to use the returnednextIdin 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: