blueChair
blueChair

Reputation: 155

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">
    <thead>
     <tr>
        <th><em class="fa fa-cog"></em></th>
        <th class="hidden-xs">ID</th>
        <th>Patient Name</th>
        <th>Day</th>
        <th>Time</th>
        <th>Location</th>
     </tr>
    </thead>
    <tbody>
        {% for appointment in appointments %}
            <tr>
                <td align="center">
                    <button class="delete_button" id="{{ appointment.id }}">
                        <em class="fa fa-trash"></em>
                    </button>
                </td>
                  <td>1</td>
                <td class="hidden" id="appointment_id">{{ appointment.id }}</td>
                <td>{{ appointment.patient }}</td>
                <td>{{ appointment.day }}</td>
                <td>{{ appointment.time }}</td>
                <td>{% if appointment.clinic %}
                      {{ appointment.clinic }}
                      {% endif %}
                      {% if appointment.hospital %}
                      {{ appointment.hospital }}
                      {% endif %}
                </td>
            </tr>
        {% endfor %}
    </tbody>
</table>

Javascript is as below :

$(document).ready(function(){
    $(".delete_button").click(function() {
        var id = $(this).attr('id');
        $.ajax({
            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 ?

EDIT 2 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 ?

Upvotes: 1

Views: 2715

Answers (1)

Sayse
Sayse

Reputation: 43300

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 }}");

Upvotes: 6

Related Questions