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'开发者_如何学JAVA)
.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
That is because $.get
is performed asynchronously (that is what A
in AJAX
means)
You can:
- Change the
$.get
to$.ajax
and make it synchronous withasync: false
option - (preferred) To perform all your work in
$.get
callback
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},
);
}
});
});
精彩评论