I am using JQuery 3.6 in a page.
I want to avoid unnecessary trips to the server, so I am using a data-attribute data-fetched
to set a flag to determine whether the trip to the server should be made or not.
Here is the relevant line in my HTML markup:
<li><a class="nav-link" data-fetched="0" href="#foo" data-url="/some/path/endpoint" data-csrf="09i9i90203r30rce" data-toggle="tab">Tab One</a></li>
The Javascript code that handles this is shown below:
$().ready(function() {
// Posts
$('a.nav-link[data-url]').on('click', function(e){
console.log('Element with href: ' + $(this).attr('href') + ' clicked!');
let selected_elem = $(this);
let fetched = parseInt( $(this).data('fetched') );
let elem_to_update = $(this).attr('href');
console.log('data-fetched attribute value: ' + selected_elem.data('fetched'));
if (fetched == 1){
console.log('Data already fetched from server')
} else {
$.ajax({
type: 'POST',
url: $(this).data('url'),
headers: {
'X-CSRFToken': $(this).data('csrf'),
},
dataType: 'html',
success: function(data, textStatus, jqXHR){
selected_elem.attr('data-fetched','1');
$(elem_to_update).html(data)
},
error: function (jqXHR, textStatus, errorThrown ) {
console.log(textStatus);
alert(" Can't do because: " + errorThrown);
},
});
}
});
When I run this code, I always get the following output in the console:
data-fetched attribute value: 0
Why is the variable value not being correctly read in my script - even though it the HTML variable is being set correctly?
How do I fix this?