Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda