Jquery Promise Wait To Ajax End
I'm getting predefined values, which i have to insert into two selects:
Solution 1:
You need to set the promise from the ajax like so:
(function($) {
// Our Ajax promise variable
var promise;
$('#first').change( function() {
// Set the ajax promise variable
promise = $.ajax({
url: "#"
}).done(function() {
$('#second').append(
'<option value="a">a</option>'+
'<option value="b">b</option>'+
'<option value="c">c</option>'
);
console.log('appending new content...');
});
});
$('#first').val('2').change();
// the var `promise` was set on the line above when it executed
// the `change()` callback
promise.promise().done( function() {
$('#second').val('b');
console.log('setting value...');
});
})(jQuery);
JSFiddle: http://jsfiddle.net/W2nVd/2/
Solution 2:
Perhaps I'm missing some of your workflow requirements, but can't you just set the value of #second after you append the options?
$.ajax({
url: "#"
}).done(function() {
$('#second').empty().append(
'<option value="a">a</option>'+
'<option value="b">b</option>'+
'<option value="c">c</option>'
);
$('#second').val('b');
console.log('appending new content...');
});
Updated fiddle: http://jsfiddle.net/W2nVd/1/
Solution 3:
.done() is exactly what you are searching for just put it inside..like so
try ...
$('#first').change( function() {
$.ajax({
url: "giveMeValues.phpOrWhatever"
}).done(function() {
// just simulating data from ajax call
$('#second').append(
'<option value="a">a</option>'+
'<option value="b" selected="selected">b</option>'+
'<option value="c">c</option>'
);
});
});
.... or.....
$('#first').change( function() {
$.ajax({
url: "giveMeValues.phpOrWhatever"
}).done(function() {
// just simulating data from ajax call
$('#second').append(
'<option value="a">a</option>'+
'<option value="b">b</option>'+
'<option value="c">c</option>'
);
$('#second').val('b'); // change value after options are available
});
});
Post a Comment for "Jquery Promise Wait To Ajax End"