I struggled with AJAX when I started with Django due to a lack of JS experience.
I will give you an example of the aync form that I use to add parameters and display parameters.
The trendy code for my template is as follows, and it will work just as well as the form you rendered, and not my lazy hardcoded html.
<div class="modal" id="AddOptions" style="display:none;"> <div class="modal-header"> <button class="close" data-dismiss="modal">X</button> <h3>Add Options</h3> </div> <div class="modal-body"> <form id="OptionForm" action="." method='POST'> <div id="OptionValueError" class="control-group"> <span class="help-inline"></span><br> <br>Value <input type="text" name="OptionValue" id="id_OptionValue" /><br>Label <input type="text" name="OptionLabel" id="id_OptionLabel"/><input type="hidden" name="VariableID"> </div> <div id="divid_OptionTable"> <table class="table table-condensed" id="OptionTable"> <thead> <th>Value</th> <th colspan="2">Label</th> </thead> <tbody> </tbody> </table> </div> </div> <div class="modal-footer"> <input type="submit" class="btn btn-primary" value="Add"> <button type="reset" class="btn">Reset</button> </form> </div> </div>
Then, make sure you have the following CSRF token issues at your disposal.
<script type="text/javascript"> jQuery(document).ajaxSend(function(event, xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function sameOrigin(url) { // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute ie relative. !(/^(\/\/|http:|https:).*/.test(url)); } function safeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } if (!safeMethod(settings.type) && sameOrigin(settings.url)) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } }); </script>
Secondly, this is what the main AJAX POST will look like using jQuery. Please note that it is based on preventing the behavior of the default presentation of a form living in our modal mode. Upon successful addition of newly added values ββto the table. It would not be so difficult to add values ββas part of capturing the form, but I like to be sure that everything has been saved and processed before being added to the table.
$(document).ready(function() { $("#OptionForm").submit(function(event){ event.preventDefault(); $.ajax({ type:"POST", url:"{% url builder.views.addoption %}", data: {VariableID: $('input:hidden[name=VariableID]').val(), OptionLabel: $('input:text[name=OptionLabel]').val(), OptionValue: $('input:text[name=OptionValue]').val()}, success: function(data){ console.log(data['OptionID']); $("#OptionValueError").removeClass("error"); $("#OptionValueError span").text(""); $("#OptionValueError span").removeClass("error"); $('#OptionTable > tbody:last').append('<tr id=Option_'+data['OptionID']+'><td>'+data['OptionValue']+'</td><td>'+data['OptionLabel']+'</td><td><a href="#" onClick="deleteOption('+data['OptionID']+')"><i class="icon icon-remove"></i></a>'); $('input:text[name=OptionValue]').val(''); $('input:text[name=OptionLabel]').val(''); } }); }); });
Finally, you just need a view that captures this AJAX request, which will look like this partially written below.
def addoption(request): if request.is_ajax(): OptionValue = int(request.POST['OptionValue']) OptionLabel = request.POST['OptionLabel'] VariableID = int(request.POST['VariableID']) getVar = Variable.objects.get(id=VariableID) newOption = Option(VariableID=getVar, Value=OptionValue, Label=OptionLabel) newOption.save() response = {'OptionValue': OptionValue, 'OptionLabel': OptionLabel, 'OptionID': newOption.id} json = simplejson.dumps(response) return HttpResponse(json, mimetype="text/json") else: pass
The dict answer that we serialize json is what is returned as data and subsequently used to add values ββto the table. All without reloading the main page.
Hope this example helped. Let me know if you have any questions.
Jd