mrkre
mrkre

Reputation: 1548

jQUery+Django Modal Form Async Submission No Page Refresh

This topic has been addressed several times but I can't seem to get it to work:

How do I insert a django form in twitter-bootstrap modal window?

Asynchronous forms with bootstrap and django

Simple Django form in Twitter-Bootstrap modal

http://www.micahcarrick.com/ajax-form-submission-django.html

I have a table of items, each row with an edit button attached. When clicked, the modal form for UpdateView is shown. I am able to retrieve the correct records but on submission, I am unable to obtain aysnc submission such that the page does not redirect.

My form:

class RSVPForm(forms.ModelForm):
    class Meta:
        model=RSVP
        fields = ['status', 'notes', 'comments']

Views - UpdateView that inherits AjaxableResponseMixin found in django docs:

import json

from django.http import HttpResponse
from braces.views import LoginRequiredMixin
from django.views.generic import UpdateView

class AjaxableResponseMixin(object):
    def render_to_json_response(self, context, **response_kwargs):
        data = json.dumps(context)
        response_kwargs['content_type'] = 'application/json'
        return HttpResponse(data, **response_kwargs)

    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return self.render_to_json_response(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
            }
            return self.render_to_json_response(data)
        else:
            return response

class RSVPUpdateView(LoginRequiredMixin, AjaxableResponseMixin, UpdateView):
    model = RSVP
    form_class = RSVPForm
    template_name = 'rsvp/rsvp_modal.html'
    success_url = reverse_lazy('rsvp:rsvp_list')

Js:

$(document).ready(function(){
    $('.rsvp-form').submit(function() {
        $.ajax({ 
            type: $(this).attr('method'), 
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function() { // on success..
                $('#success_div').append('Changes saved'); // update the DIV
                $('#success_div').toggleClass('alert alert-success'); // unhide
            },
            error: function(xhr, ajaxOptions, thrownError) { // on error..
                $('#error_div').append(xhr); // update the DIV
                $('#error_div').toggleClass('alert alert-error'); // unhide
            }
        });
        return false; 
    });
});

I'm not exactly sure why return false; in the js is not suppressing the form submission. I tried using e.preventDefault(); but with no results. I think it's an oversight somewhere and would appreciate it if someone can spot it. Perhaps a change to the AjaxableResponseMixin?

Edit: Added template

In modal form's template:

{% load crispy_forms_tags %}
<div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
         <div id="success_div" class="alert alert-success hide"><button type="button" class="close" data-dismiss="alert">&times;</button></div>
         <div id="error_div" class="alert alert-error hide"><button type="button" class="close" data-dismiss="alert">&times;</button></div>
         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
         <h4 class="modal-title">RSVP Details</h4>
      </div>
      <!-- form here -->
      <form class="rsvp-form" method="post" action="{% url 'rsvp:rsvp_update' pk=form.instance.id %}">
      <div class="modal-body">
         {% crispy form form.helper %}
      </div>
      <div class="modal-footer">
        <input class="btn btn-primary" id="modal-submit" type="submit" value="Save" />
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
      </form>
    </div>
</div>

This form is displayed using the following js:

$(document).ready(function(){
    $('.edit-modal').click(function(ev) { // for each update url
        ev.preventDefault(); // prevent navigation
        var url = $(this).data('form'); // get the update form url
        $('#RSVPModal').load(url, function() { // load the url into the modal
            $(this).modal('show'); // display the modal on url load
        });
        return false; // prevent click propagation
    });
});

Upvotes: 0

Views: 5350

Answers (1)

Hieu Nguyen
Hieu Nguyen

Reputation: 8623

I see, the form is loaded dynamically in a modal. In this case you need to bind the submit event handler after the form has been rendered to browser or use on():

$(document).ready(function(){
    // use on() to bind event handler here
    $('#RSVPModal').on('submit', '.rsvp-form', function () {
        $.ajax({
            type: $(this).attr('method'), 
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function() { // on success..
                $('#success_div').append('Changes saved'); // update the DIV
                $('#success_div').toggleClass('alert alert-success'); // unhide
            },
            error: function(xhr, ajaxOptions, thrownError) { // on error..
                $('#error_div').append(xhr); // update the DIV
                $('#error_div').toggleClass('alert alert-error'); // unhide
            }
        });
        return false; 
    });

    $('.edit-modal').click(function(ev) { // for each update url
        ev.preventDefault(); // prevent navigation
        var url = $(this).data('form'); // get the update form url
        $('#RSVPModal').load(url, function() { // load the url into the modal
            $(this).modal('show'); // display the modal on url load
        });
        return false; // prevent click propagation
    });
});

Hope it helps.

Upvotes: 2

Related Questions