Reputation: 13
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
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
Reputation: 254886
That is because $.get
is performed asynchronously (that is what A
in AJAX
means)
You can:
$.get
to $.ajax
and make it synchronous with async: false
option$.get
callbackUpvotes: 4