Last active
December 19, 2015 23:18
-
-
Save mcantelon/6033205 to your computer and use it in GitHub Desktop.
AJAX group creation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
************************************************** | |
Django template: | |
************************************************** | |
<form id='group_selector_form'> | |
<select id='group_selector'> | |
{{ for group in groups }} | |
<option value='{{ group.id }}'>{{ group.name }}</option> | |
{{ endfor }} | |
</select> | |
<p>New group? <input id='new_group_name' /></p> | |
<input type='submit' value='Add Group'/> | |
</form> | |
<!-- JQuery to add submission logic to add groups --> | |
<script> | |
$(document).ready(function() { | |
$('#group_selector_form').submit(function() { | |
var group_name = $('#new_group_name').val(); | |
if (group_name != '') { | |
var data = {'group_name': group_name}; | |
$.ajax( | |
'url': '/groups/add', | |
'type': 'POST', | |
'data': data, | |
'success': function(result) { | |
// create new option element and add to selector | |
var $newOption = $('<option></option>'); | |
$newOption.attr('value', result.group_id); | |
$newOptions.text(result.group_name); | |
$('#group_selector').append(newOption); | |
// blank group name form field | |
$('#new_group_name').val(''); | |
}, | |
'error': function() { | |
alert('Unable to add group.'); | |
} | |
} else { | |
alert('Enter a group name.'); | |
} | |
); | |
}); | |
}); | |
</script> | |
************************************************** | |
View implementing /groups/add endpoint: | |
************************************************** | |
import simplejson | |
... | |
def group_add(request): | |
if request.method == 'POST': | |
# put logic to add the group here | |
# cook up a JSON response | |
response = { | |
'group_id': group.pk | |
} | |
# return data as JSON | |
return HttpResponse( | |
simplejson.JSONEncoder(encoding='utf-8').encode(response), | |
mimetype='application/json' | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment