How to update data attribute on Ajax complete

- 1 answer

Ad

I'm using October CMS and in the framework I can make an AJAX call using the following HTML element:

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="#" class="sbutton" data-request="onSavedeal" 
     data-request-data="deal_ID:'14779255',type:'local',active:'0'">
    <i class="material-icons pink-text listfavorite">favorite</i>                      
</a>

Whenever this link is clicked on a favorite button fires off an update to a controller "onSavedeal". Updating the database works fine on the first click. However, after updating, the value for the "data-request-data" attribute isn't updated so the button does not work for subsequent clicks.

I need to make the link change so that "active:'0'" becomes "active:'1'". The resulting full element would be

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="#" class="sbutton" data-request="onSavedeal" 
     data-request-data="deal_ID:'14779255',type:'local',active:'1'">
    <i class="material-icons pink-text listfavorite">favorite</i>                      
</a>

In the framework I can add another attribute called "data-request-success" which executes a javascript function (or code) up successful completion of the AJAX call. How can I make a function called "updateactive()" which would toggle the active value between 0 and 1. The final element should look like:

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="#" class="sbutton" data-request="onSavedeal" 
     data-request-data="deal_ID:'14779255',type:'local',active:'0'"
     data-reuqest-success="updateactive();">
    <i class="material-icons pink-text listfavorite">favorite</i>                      
</a>
Ad

Answer

Ad

If you can safely identify this a element by attribute data-request having value onSavedeal, you would write the updateactive function as follows:

function updateactive() {
    var newAttrValue = "deal_ID:'14779255',type:'local',active:'1'";
    $('[data-request="onSavedeal"]').attr('data-request-data', newAttrValue);
 }

Don't forget to correct data-reuqest-success to data-request-success.

UPDATE If you have many a elements on the page, you can reuse same function like below. Check demo - Fiddle .

function updateactive() {
    var clickedA = event.currentTarget,
        newAttrValue = $(clickedA).attr('data-request-data').replace("active:'0'", "active:'1'");

    $(clickedA).attr('data-request-data', newAttrValue);
}
Ad
source: stackoverflow.com
Ad