#StackBounty: #javascript #jquery #node.js #ajax jquery ajax request to nodejs server only works on page refresh

Bounty: 50

I am quite new to ajax and I am not sure what I am doing wrong. I have a webpage that fetches all comments on a post with an ajax get request. The issue is that the ajax request is only succesful after the webpage is refreshed. I disabled the cache to see if that would solve the issue, but it didn’t.

For example, when I fetch the first comments after refreshing the page from post A and then go onto post B on the website, the comments from the post A appear as the comments for post B, then when I refresh the page the comments for post B are replaced with post B’s comments successfully.

I am using jQuery to make the request:

$.ajax({
    type: "GET",
    url: someURL,
    success: (comments) => {
        console.log(comments);
    
        comments.questions.forEach(questionComment => {
            $('.questionComments').append(
                `<div class="comment">
                    <p>${questionComment.content}</p>
                </div>
                `
            )
        });
    
    
        comments.answers.forEach(answer => {
            answer.forEach(answerComment => {
                $(`.answer#${answerComment.forId} .answerComments`).append(
                    `<div class="comment">
                    <p>${answerComment.content}</p>
                </div>
                `
                )
            })
        })
    },
    cache: false
})

What the commets object looks like brefore the reload – a blank objectblank object

What the comments object looks like after the reloadenter image description here

When you navigate to a different post / different url, the object from the previous post / url is the initial object on the new post, and then when you reload the page the correct object is fetched.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.