I have a drop-down list and I want to let the user add a new option to it while staying on the same page. I'm trying to do it with a modal. Here's the flow:
- User clicks a button on the main form and a modal pops up with an "Add Reward" form
- User inputs data and hits submit
- Success --> modal closes and drop-down updates with newly added item
Failure --> modal shows form errors like a normal form and lets user re-submit
edit_goals.html
{% load crispy_forms_tags %}
<form method="post" novalidate>
{% crispy form %}
</form>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<form method="post" id="addRewardForm" novalidate
data-addreward-url="{% url 'wakemeup:ajax_add_reward' %}"
>
{% crispy addRewardForm %}
</form>
</div>
</div>
</div>
</div>
<script>
$("#addRewardForm").submit(function() {
var url = $("#addRewardForm").attr("data-addreward-url");
$.post(
{
url:url,
data: {
CSRF: getCSRFTokenValue()
},
success: function(data, status){
alert("Data: " + data + "\nStatus: " + status);
}
}
);
return false // Ignore original submit button
});
</script>
views.py
def addreward(request):
if request.method == 'POST':
# Create form instance and bind data
form = RewardForm(request.POST)
if form.is_valid():
# Create / save new reward
myreward = Reward(
rewardid = form.cleaned_data.get('rewardid'),
rewardname = form.cleaned_data.get('rewardname'),
)
myreward.save()
# Return nothing
return HttpResponse('Added Successfully')
return render(request, 'edit_form.html', {'form': form})
The problem
The callbacks are not being called. When you click submit on the modal form, it processes the new reward and saves it fine. But instead of storing the return data from the view to the data
variable of the success()
callback, it just shows the rendered output from the view and redirects to a different page.
What I want is to capture the rendered output to the data
variable of the $.post()
call so I can then display the HTML inside the modal as I please.
I tried converting $.post()
to $.ajax()
and including the error
callback, but nothing. The success callback doesn't even return a simple alert()
either.
I am doing similar processing with GET requests and the callback works fine there. What am I missing here?