Wolrab Wolrab - 1 year ago 46
Ajax Question

Updating data attribute after ajax call

I have a page which lists a number of jobs, each job has a button for paid and the button has a data-paid attribute which contains the value of whether it's paid or not.

When the button is clicked, I send a request to my route which updates the payment and returns success along with the status whether its paid or not.

See my button.

<button data-id="{{ $r->id }}" data-paid="{{ $r->paid }}" class="btn btn-success btn-sm paid">Paid</button>

When clicked

$('button.paid').on('click', function() {

var job = this;
var id = $(this).data("id");

$.get('/round/job/' + id + '/paid', function(data){





When looking at the console, if paid the route returns 1, if not paid it returns 0.

I want to update the data-paid attribute against the button with the value of either 1 or 0.

I thought function would do that but it doesn't update the value it remains at the value when the page is loaded.

Answer Source

data is not an accessor for data-* attributes, it's both more and less than that. data manages jQuery's data cache for the element, which is only initialized from the data-* attributes. It never writes to them.

To actually change the attribute value, use attr, not data:

$(job).attr("data-paid", dta.jh.paid);

Of course, if you use data throughout your code, and don't care about the actual attribute value except as a starting point, data is fine, just don't expect the attribute value to change when you change the data value.

The flip side is that if you don't need the additional features data provides, just use attr.


// Get the element
var t = $("#target");

// See what its data value for "foo" is
console.log("Before: t.data('foo') = " + t.data('foo'));

// See what its *attribute* is
console.log("Before: t.attr('data-foo') = " + t.attr('data-foo'));

// Change it
t.data('foo', 'updated');

// See what its data value for "foo" is again
console.log("After:  t.data('foo') = " + t.data('foo'));

// See what its *attribute* is again:
console.log("After:  t.attr('data-foo') = " + t.attr('data-foo'));
<div id="target" data-foo="bar"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>