Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
How to ensure fetch GET request runs after database updated?

I am having trouble ensuring that my GET request in Javascript runs after my PUT.

Sometimes the JSON promise returns with updated data sometimes it does not!

It appears to be random. It always displays correctly upon page reload.

I am getting a "Fetch failed loading: PUT" error in my console despite the database being updated successfully.

I know of await/async but was unclear if this was my solution and if so how I would implement with the correct syntax.

Here is my JS:

function like(id) {

    like_button = document.getElementById(`like-button-${id}`);
    
    if (like_button.style.backgroundColor == 'white') {
        fetch(`/like/${id}`, {
            method:'PUT',
            body: JSON.stringify({
                like: true
            })
        });

        like_button.style.backgroundColor = 'red';
    }
    else {
        fetch(`/like/${id}`, {
            method:'PUT',
            body: JSON.stringify({
                like: false
            })
        });

        like_button.style.backgroundColor = 'white';


    }

    fetch(`/like/${id}`)
    .then(response => response.json())
    .then(post => {
        like_button.innerHTML = post.likes;
    });

}

In case it is helpful here is my view in views.py:

@csrf_exempt
def like(request, id):
    post = Post.objects.get(id=id)
    user = User.objects.get(username=request.user.username)

    if request.method == "GET":
        return JsonResponse(post.serialize(), safe=False)

    if request.method == "PUT":
        data = json.loads(request.body)
        print(data.get("like"))
        if data.get("like"):
            post.Likes.add(user)
        else:
            post.Likes.remove(user)
        post.save()
        return HttpResponse(status=204)

Console error message

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!