This question already has an answer here:
I would like to change the text of each div with the class "container". I have a function test1, which will call after a click on a button. This function should change the text with return values of function test2. but the text will not be changed. alert(result)
shows the correct text which I expect. How can I solve this issue?
<div class="container">Some text</div>
<div class="container">Some text</div>
<div class="container">Some text</div>
<div class="container">Some text</div>
<div class="container">Some text</div>
function test1() {
$( ".container" ).each(function() {
$( ".container" ).text(test2('MyValue'));
})
}
function test2(value) {
$.getJSON("ajax.php", {
value: value
}, function(result) {
alert(result);
return result;
})
}
</div>
You can't change the text until the AJAX is done.. Promises are a good solution..
<div class="container">Some text</div>
<div class="container">Some text</div>
<div class="container">Some text</div>
<div class="container">Some text</div>
<div class="container">Some text</div>
function test1() {
test2('myValue').then(res=>$( ".container" ).text(res))
}
function test2(value) {
return new Promise(done=>
$.getJSON("ajax.php", {
value: value
}, function(result) {
done(result);
}));
}