Home > Enterprise >  What is the best way to pass django form data to javascript ajax call?
What is the best way to pass django form data to javascript ajax call?

Time:10-05

I have a form with a certain number of fields and using a ajax call to communicate with the server. And I was wondering what is the best way to pass the data that I get from the request.post of the form and pass it back to the javascript success property of the ajax.

Here is an example:

def ajaxView(request):
form = MyForm(request.POST or None)
if request.is_ajax() and form.is_valid():
    #1 I used to use render_to_string and Parse it in the js
    #2 or get field by field using the request.POST.get method and return it
    #3 is to serialize the form

    return JsonResponse({})
return ""

In the js file:

function CreateAjax(e) {
e.preventDefault();

$.ajax({
    url: "/ajaxViewUrl/",
    type: "post",
    data: $("#idForm").serialize(),
    success: function (data) {
      // if the first option retreive fields by field after parse
    },
    error: () => {

    }
});

}

Now this would not be an issue if the form has a small number of fields, my concern is when the form has a considerable number of fields and in any cases I would like to reduce repetition of getting the value of the inputs in the form.

CodePudding user response:

Something to look out for is when returning the form as an html snipped to a modal.

Views.py

@require_http_methods(["POST"])
def login(request):
form = BasicLogInForm(request.POST)
    if form.is_valid():
        print "ITS VALID GO SOMEWHERE"
        pass

    return render(request, 'assess-beta/login-beta.html', {'loginform':form})

Simple view to return the html snipped

Form html Snipped

<form class="login-form" action="/login_ajx" method="Post"> 
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="header">Authenticate</h4>
  </div>
  <div class="modal-body">
        {%if form.non_field_errors %}<div class="alert alert-danger">{{ form.non_field_errors }}</div>{%endif%}
        <div class="fieldWrapper form-group  has-feedback">
            <label class="control-label" for="id_email">Email</label>
            <input class="form-control" id="{{ form.email.id_for_label }}" type="text" name="{{ form.email.html_name }}" value="{%if form.email.value %}{{ form.email.value }}{%endif%}">
            {%if form.email.errors %}<div class="alert alert-danger">{{ form.email.errors }}</div>{%endif%}
        </div>
        <div class="fieldWrapper form-group  has-feedback">
            <label class="control-label" for="id_password">Password</label>
            <input class="form-control" id="{{ form.password.id_for_label }}" type="password" name="{{ form.password.html_name}}" value="{%if form.password.value %}{{ form.password.value }}{%endif%}">
            {%if form.password.errors %}<div class="alert alert-danger">{{ form.password.errors }}</div>{%endif%}
        </div>
  </div>
  <div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input type="submit" value="Sign in" class="btn btn-primary pull-right"/>
</div>
</form>

Page containing the modal

{% include "assess-beta/login-beta.html" %}

Use the include tag to load the snipped on page load so it is available when you open the modal.

Modal.js

$(document).on('submit', '.login-form', function(){
$.ajax({ 
    type: $(this).attr('method'), 
    url: this.action, 
    data: $(this).serialize(),
    context: this,
    success: function(data, status) {
        $('#LoginModal').html(data);
    }
    });
    return false;
});

Using the .on() in this case work like .live() the key being binding the submit event not to the button but to the document.

  • Related