Carson D
Carson D

Reputation: 91

Function not defined when using promises inside AJAX call

Context

I'm trying to load in the like count of messages received from my database. I do this by executing an AJAX call that works fine and obtains the messages from the database, like so:

function getThreads() {

    $.ajax({
        url: 'includes/index/getForums.php',
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            data.forEach(function(item) {

                if (item.error == undefined) { //if not empty

                    let newContent =
                    //insert content here (I removed it for simplicity's sake)

                    let appended = $(newContent).appendTo(".threadsContainer");

                    ///start of the code in question
                    var forumId = $(appended).find(".forum_id").val();
                    var idUsers = $(appended).find(".idUsers").val();

                    var checkLike = checkLike(idUsers, forumId);
                    checkLike.done(function(data) {

                        console.log(data);

                    });
                    //end of the code in question

                }

            });
        }
    });

}

After receiving the messages from the database, I want to check the like count of each message, so I include a promise:

var checkLike = checkLike(idUsers, forumId);
checkLike.done(function(data) {

    console.log(data);

});

The function checkLike is as follows:

function checkLike(idUsers, forumId) {

    return $.ajax({
        url: 'includes/replyThread/checkLike.php',
        type: 'POST',
        data: {idUsers: idUsers, forumId: forumId}
    });

}

Problem

My problem is that, instead of logging the data, I get an error message that says:

Uncaught TypeError: checkLike is not a function

Question

How can I alter this code so that the function is considered as a function? I've used similar code on other pages on the same website and they have worked fine. I'm not sure if I'm missing something simple or if I lack an understanding somewhere. Any ideas? Let me know if there's any confusion. Thanks.

Upvotes: 1

Views: 91

Answers (1)

Carson D
Carson D

Reputation: 91

I found a solution - I just changed the name of the variable that calls the checkLike function to var checkLikeCount = checkLike(); instead of var checkLike = checkLike();. This might be the solution to this sort of problem.

Upvotes: 1

Related Questions