Reputation: 169
I have this AJAX call that I make after a button click in the HTML code:
HTML:
<div id="singlemethod">
<input type="hidden" id="teachersol" value="">
[...]
<button type="button" id="run" onclick="javascript:play(1, 105, 2)">
<img src="./images/green_play.png" width="40px" height="40px"> </button>
</div>
JAVASCRIPT/AJAX:
function play(mn, id, nofm) {
for (i=1; i<=nofm; i++)
getSolution (i, id, mn);
executemethod (mn, id);
}
function getSolution (mn, id, actmn) {
$.ajax({
type: "GET",
url: "ajax/getteachsol.php",
data: "id="+id+"&number="+mn,
success: function(data){
$('#teachersol').val(data);
}
});
return false;
}
function executemethod (mn, id) {
var teach= document.getElementById('teachersol').value;
alert (teach);
[...]
}
if I check the value with the alert it prints nothing, but if I inspect the element with Chrome I see what I expect in the value field. Any idea of why it's not printing anything in the executemethod? May be a problem with the AJAX (I'm pretty new at it)? If you need any additional information just ask! Thank you!
Upvotes: 0
Views: 4984
Reputation: 8181
Building on dholakiyaankit's answer...
Based on this:
<input type="hidden" id="teachersolution" value="">
Shouldn't it be:
var teach= document.getElementById('teachersolution').value;
and
$('#teachersolution').val(...)
as element with id "teachersol" does not exist!
EDIT:
also try:
success: function(data){
$('#teachersol').val(data);
$('#teachersol').promise().done(function(){
executemethod (mn, id);
});
}
Upvotes: 0
Reputation: 169
I've solved the problem using complete
in the ajax call. Here's the working code:
function getSolution (mn, id, actmn) {
$.ajax({
type: "GET",
url: "ajax/getteachsol.php",
data: "id="+id+"&number="+mn,
success: function(data){
$('#teachersol').val(data);
},
complete: function () {
executemethod (mn, id);
}
});
return false;
}
Upvotes: 0
Reputation: 2459
A in AJAX is asynchronous which means execution of executemethod()
can be done before your ajax call finishes.
Put executemoethod()
in for example success function of ajax to ensure it is executed after ajax call finishes or go one step further and look for promises in jquery: http://api.jquery.com/promise/
Upvotes: 1
Reputation: 13801
function getSolution (mn, id, actmn) {
$.ajax({
type: "GET",
url: "ajax/getteachsol.php",
data: "id="+id+"&number="+mn,
success: function(data){
$('#teachersol').val(data);
executemethod (mn, id);
}
});
return false;
}
Please change you code little bit you can call Executemethod inside ajax function
function play(mn, id, nofm) {
for (i=1; i<=nofm; i++)
getSolution (i, id, mn);
//and remove from here
}
now check are you getting same result? i have not tested it although
Reason because your alert is calling before ajax gets completed
Upvotes: 2