Home > other >  Why can not access parameter of parent ajax call into child ajax call
Why can not access parameter of parent ajax call into child ajax call

Time:12-08

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)

CodePudding user response:

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 with let instead of var:

for (let i = 0; i < res.length; i  ) {

CodePudding user response:

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.

//First ajax:  return comments
function func_GetComments() {
    return new Promise(function (resolve, reject) {
        $.ajax({
            type: "GET",
            url: "/meetzen/comments",
            data: { acId: accountId, pstId: postId },
            success: function (res) {
                if (res.length > 0) {
                    resolve(res);
                }
                else {
                    reject("true");
                }
            }
        });
    });
}

//second ajax, read comment on success block. data: { commentId: comment.comment_id }, here use comment object to get id

function GetLikeOrNotImgZoom(comment) {
    $.ajax({
        type: "GET",
        url: "/meetzen/getlikeornotimgzoom",
        data: { commentId: comment.comment_id },
        success: function (likeornot) {

            if (likeornot == 0) {
                //i have chaned syntex to concat string, apply in else as well to better perfromace.
                $("#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>");
            }
        }
    });
}

its always matter which way we are calling ajax.

Main starting thread refer promise : https://www.w3schools.com/js/tryit.asp?filename=tryjs_promise2

let IPromiseToReturnComments = func_GetComments();
IPromiseToReturnComments.then(() => {
    //here value is comments which is return by func_GetComments promise.
    $.each(value, (index, comment) => {
        GetLikeOrNotImgZoom(comment);
    });
});
  • Related