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

127
Views
Send data to database via fetch and subsequently display this data to html page via fetch again without submitting form or refreshing the page

I have a django app. I'm typing a comment in a form and I'm sending it to my database via fetch.

my js code

document.getElementById("comment-form").onsubmit = function write_comment(e) {
        e.preventDefault();
        const sxolio = document.getElementsByName("say")[0].value;

        fetch('/comment', {
        method: 'POST',
        body: JSON.stringify({
            say: sxolio
        })
    })
    .then(response => response.json())
    .then(result => {
    //print result
    console.log(result);
}); 

my views.py

@requires_csrf_token
@login_required(login_url = 'login')#redirect when user is not logged in
def comment(request):
    if request.method != 'POST':
        return JsonResponse({"error": "POST request required."}, status=400)
    new_comment = json.loads(request.body)
    say = new_comment.get("say", "")
    user = request.user
    comment = Comment(
        user = user,
        say = say,
        photo = Userimg.objects.get(user = user).image
        )
    comment.save()
    return JsonResponse({"message": "Comment posted."}, status=201)

Next thing i wanna do is to display this comment and all the other data from my db, to my html page without refreshing.The moment i push the post button i want the comment to be dispayed. I dont want to update the page with some element.innerHTML = data.

my js code

function display_comments() {
    fetch('/all_comments') 
  .then(response => response.json())
  .then(all_comments => {
   do some stuff

my views.py

@login_required(login_url = 'login')#redirect when user is not logged in
def all_comments(request):
    all_comments = Comment.objects.order_by("-date").all()
    print(all_comments[0].serialize())
    return JsonResponse([comment.serialize() for comment in all_comments], safe=False)

If i use preventDefault i can see that my db is been updated but i can't retrieve the data. If i skip prevent default everything works fine but my page is refreshing simultaneously. Is there any way to do them both without refreshing the page?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The most likely problem is that your all_comments view request is being made before the comment has finished saving to the DB.

It is important that the response for comment is completely returned before the fetch to all_comments is started. You can accomplish this by doing the following...

function display_comments() {
    fetch('/all_comments') 
    .then(response => response.json())
    .then(all_comments => {
        console.log(all_comments);
    });
}

document.getElementById("comment-form").onsubmit = function write_comment(e) {
    e.preventDefault();
    const sxolio = document.getElementsByName("say")[0].value;

    fetch('/comment', {
        method: 'POST',
        body: JSON.stringify({
            say: sxolio
        })
    })
    .then(response => response.json())
    .then(result => {
        // print result
        console.log(result);

        // The request to /comment has finished it is now safe to request all 
        // comments.
        display_comments();
    });
} 
about 4 years ago · Juan Pablo Isaza Report
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!