Abin Benny
Abin Benny

Reputation: 145

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?

Upvotes: 1

Views: 641

Answers (2)

Tine S Tsengwa
Tine S Tsengwa

Reputation: 144

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.

Upvotes: 2

TheWhiteFang
TheWhiteFang

Reputation: 783

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.

Upvotes: 0

Related Questions