[javascript] How to POST the data from a modal form of Bootstrap?

I have a page using a modal to get the users email and I want to add it to a list of subscribers (which is a Django model). Here is the modal code for that:

<div id="notifications" class="modal hide fade" role="dialog" ara-labelledby="Notification" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>
        <h4>Subscribe to Status Notifications</h4>
    </div>
    <form>
        <div class="modal-body">
            <input type="email" placeholder="email"/>
            <p>This service will notify you by email should any issue arise that affects your plivo service.</p>
        </div>
        <div class="modal-footer">
            <input type="submit" value="SUBMIT" class="btn"/>
        </div>
    </form>
</div>

I tried to look in the Twitter Bootstrap doc but it really is minimal. I want to POST the data to a Django view that's listening forPOST` requests.

This is the bare essential. I am using regex to compare the format of the email before storing the email id. So if the email does not match the regex the view returns an Invalid Email. So I would like to notify the user about that within the modal itself. But I really have no idea as to how to do this. Someone please help.


UPDATE 1

Tried this based on karthikr's answer:

<form id="subscribe-email-form" action="/notifications/subscribe/" method="post">
    <div class="modal-body">
    <input type="email" placeholder="email"/>
        <p>This service will notify you by email should any issue arise that affects your service.</p>
    </div>
    <div class="modal-footer">
    <input id="subscribe-email-submit" type="submit" value="SUBMIT" class="btn" />
    </div>
</form>

<script>
    $(function(){
       $('subscribe-email-form').on('submit', function(e){
            e.preventDefault();
            $.ajax({
                url: "/notifications/subscribe/",
                type: "POST",
                data: $("subscribe-email-form").serialize(),
                success: function(data){
                    alert("Successfully submitted.")
                }
            });
       }); 
    });
</script>

There is something that is confusing me. What about the onclick event of the modal button?

I got it! I added name="Email" in the line <input type="email" placeholder="email"/>

The Django field is looking for the Email Field. So in my Django view the code is:

request.POST.get("Email", '')

So specifying the field name helps. But it takes me to the URL where I am posting. I want it to display a alert in the same page.


UPDATE 2

So part 1 is working. As in the posts are working. Now I need to show a modal for the success or failure.

Here's what I am trying. So I created this modal with a textarea:

<div id="subscription-confirm" class="modal hide fade in" aria-hidden="true">
    <div class="modal-header">
        <label id="responsestatus"></label>
    </div>
</div>

And the JavaScript:

<script>
    $(function(){
        $('#subscribe-email-form').on('submit', function(e){
            e.preventDefault();
            $.ajax({
                url: 'notifications/subscribe/',
                type: 'POST',
                data: $('#subscribe-email-form').serialize(),
                success: function(data){
                     $('#responsestatus').val(data);
                     $('#subscription-confirm').modal('show');    
                }
            });
        });
    });
</script>

So the modal comes up, but the data is not set into the label field of the modal.

This question is related to javascript jquery python django twitter-bootstrap

The answer is


I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.

<form name="paymentitrform" id="paymentitrform" class="payment"
                    method="post"
                    action="abc.php">
          <input name="email" value="" placeholder="email" />
          <input type="hidden" name="planamount" id="planamount" value="0">
                                <input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
                                    name="planform">

                </form>

You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button

    function form_submit() {
        document.getElementById("paymentitrform").submit();
   }  

You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.

You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.

<form asp-action="AddUsersToRole" method="POST" class="mb-3">

    @await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)

    <div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add Users to Role</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

</form>

You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action. You do not have to use ajax.

Mozilla documentation on form action


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation