Why Is My Data-id Variable Cached After A First Button Clicked In Jquery?

- 1 answer

I am working on a laravel 5 website. I am using jquery to implement a certain functionality. Below is my sample code.

$("document").ready(function() {

function completeHandler(event){
    var response = JSON.parse(;
    $('#remove_cv').removeAttr('disabled').attr('data-id', response.document_id);

function removeCV(){

    var document_id  = $(this).data('id');
    // Fire Ajax call to delete the document

        type: 'DELETE',
        url: getDomain() + 'documents/' + document_id,
        dataType: 'json',
        cache: false,
        success: function(data, textStatus){
            $('#remove_cv').attr('disabled', 'disabled');

This is my problem:

When a CV is uploaded the first time and the delete button subsequently clicked, it works perfectly. When a CV is now uploaded the second time (which successfully uploads), and the delete button clicked, it fails to delete.

First Delete

url: http://localhost:8000/documents/53

Second Delete

url: http://localhost:8000/documents/53 (Here I expected 54 or the new document_id)

Why does it use the document_id of the first call? Monitoring with console.log($('#remove_cv').attr('data-id')) in completeHandler, I see that data-id is correctly set. How can I solve this problem?



The problem is you are using data api and the attr together.

When you use data api to get data it is stored in an internal structure, so when you update the data-id using attr, only the attribute value is updated not the internal value stored by the data api.

When you have a data-* attribute, it is used to initialize the value of the data api, but once that is done those are not synchronized.

$('#remove_cv').removeAttr('disabled').data('id', response.document_id);