blueChair blueChair - 10 months ago 69
Ajax Question

Delete Model object in django Using jquery Ajax

Having a hard time deleting an object using jquery/ajax. I have implemented a table that has rows containing a list of objects from Appointment model. There is a delete button in each row.

Template for objects' table is :

<table class="table table-striped table-bordered table-list">
<th><em class="fa fa-cog"></em></th>
<th class="hidden-xs">ID</th>
<th>Patient Name</th>
{% for appointment in appointments %}
<td align="center">
<button class="delete_button" id="{{ }}">
<em class="fa fa-trash"></em>
<td class="hidden" id="appointment_id">{{ }}</td>
<td>{{ appointment.patient }}</td>
<td>{{ }}</td>
<td>{{ appointment.time }}</td>
<td>{% if %}
{{ }}
{% endif %}
{% if %}
{{ }}
{% endif %}
{% endfor %}

Javascript is as below :

$(".delete_button").click(function() {
var id = $(this).attr('id');
url: "{% url 'deleteappointment' %}",
data: { 'id' : id },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", {% csrf_token %} );
success: function(response){

Nothing is happening when I click on the delete button. What am I doing wrong here ?

This is going on in ajax request :
Syntaxerror in console :

beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", <input type='hidden' name='csrfmiddlewaretoken' value='LUgmNbcWfkIR9KpLi7lzsn0QOk' /> );

How do I prevent csrftoken tag to render the whole input field here ?

Answer Source

You're using the {% csrf_token %} template tag which inserts the token in a html format for a form. You can use the other type of brackets (inside quotes)

xhr.setRequestHeader("X-CSRFToken", {% csrf_token %} );

should be

xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");