I retrieve data from database using ajax call. In my code can not access parameter
of parent ajax call request to child ajax request call. I can see error in console. I can try to put asyc: false
in child request but using async
i can access parameter but child ajax call only work one time.
Here down is my code
$.ajax({
type: "GET",
url: "/url",
data: { acId: acId, pstId: pstId },
success: function(res) {
// res.lenth = 2
for (var i = 0; i < res.length; i++) {
$.ajax({
type: "GET",
url: "/url",
data: {commentId: res[i].comment_id},
success: function(likeornot){
if(likeornot == 0)
{
$("#btnlikeornot").append("<button type = 'submit' onclick ='btncommentunlike("+res[i].comment_id+")' id='commentunlikebtn"+res[i].comment_id+"' data-id='"+res[i].u_id+" ' class='comment-like-button-style'>" +
"<img src='https://img.icons8.com/material-outlined/24/000000/like--v1.png'/>" +
"</button>");
}
else
{
$("#btnlikeornot").append("<button type = 'submit' onclick ='btncommentlike("+res[i].comment_id+")' id='commentlikebtn"+res[i].comment_id+"' data-id='"+res[i].u_id+" ' class='comment-like-button-style'>" +
"<img src='https://img.icons8.com/material-rounded/24/fa314a/like.png' />" +
"</button>");
}
}
});
}
}
});
Error
imagezoom.js:68 Uncaught TypeError: Cannot read properties of undefined (reading 'comment_id')
at Object.success (imagezoom.js:68)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at A (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
2
Answers
The problem is the variable
i
changes before the success event occurrs, so it doesn’t have the expected value. To solve the problem you have to use a local copy of the variable for each iteration pf the loop. This can be achieved declaring the variable withlet
instead ofvar
:I don’t know the object res but here is the way you would prefer to of calling ajax in ajax without any async process. no need of for.
//second ajax, read comment on success block.
data: { commentId: comment.comment_id }, here use comment object to get id
its always matter which way we are calling ajax.
Main starting thread
refer promise : https://www.w3schools.com/js/tryit.asp?filename=tryjs_promise2