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

299
Visualizações
Django POST method is not working when using JavaScript

I am trying to display a div on submitting a form. It displays the div on submitting the form whereas form is not submitted. Here POST method is used. JavaScript is used to display the div.

html file:

                    <form method="POST" name="myFirstForm" id="chform">
                        {% csrf_token %}
                        <input type="hidden" name="details_id" value="{{details.id}}"/>
                        <input type="hidden" name="details_user_id" value="{{details.user_id}}"/>
                        <input type="hidden" name="user_id" value="{{user.id}}"/>
                        <input type="submit" class="btn btn-danger" id="chat" onclick="return myFunction()" value="Chat Now">
                    </form>
                   <div class="page-content page-container" id="page-content" style="display:none"></div>

JavaScript:

<script>
 document.forms['myFirstForm'].addEventListener('submit', function(event) {
// Do something with the form's data here
this.style['display'] = 'none';
event.preventDefault();
  });
   function myFunction() {
    var x = document.getElementById("page-content");
    if (x.style.display === "none") {
      x.style.display = "block";
    } else {
      x.style.display = "none";
    }
  }

</script>

views.py:

    if request.method=='POST':
        jid = request.POST.get('details_id')
        print(jid)
        cjid = request.POST.get('details_user_id')
        print(cjid)
        userid = request.POST.get('user_id')
        print(userid)

If I not want to display the div and removes JavaScript code , POST method works.Can anyone suggest a solution to solve this issue?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Have you considered Asynchronous JavaScript And XML (AJAX)? It sounds to me like you want asynchronous JS functionality (or I'm not understanding correctly).

So in your submit button, you would make it call an AJAX function as follows:

<button type="submit" id="chat" data-url="{% url 'url_to_your_view_handling_the_post' %}" value="Chat Now"></button>

Then your onclick function:

$(document).on('click', '#chat', function (e) {

    $.ajax({
        type: 'POST',
        url: $(this).data('url'),
        data: {
            // add any other HTML data attributes in this dictionary
            csrfmiddlewaretoken: getCookie('csrftoken'),
        },
        success: function (json_response) {
            // Successful AJAX response handling routine here
            // Display your div
            var x = document.getElementById("page-content");
            if (x.style.display === "none") {
                x.style.display = "block";
            }
            else {
                x.style.display = "none";
            }
        },
        error: function (xhr, errmsg, err) { }
    });
})

So your view at url url_to_your_view_handling_the_post defined in the button will handle the POST method and return a JSON response with whatever data you want. If it returns successfully, the success routine in your AJAX function is run.

Sending the csrf token is not extremely simple and I refer you to this thread for more about the getCookie('csrftoken') function.

Note: This is a jquery implementation of AJAX therefore you’ll need to include jquery as well in your template.

about 4 years ago · Juan Pablo Isaza Relatório

0

If you want to submit the form, then you should not call event.preventDefault();. This basically tells js to capture the submit event and prevent the default behavior of the event which is to submit the form in your case.

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