Search code examples
javascriptajaxgetelementbyid

"Add to Favorite / Remove" - Ajax not working


I want to create a "Add to favorite" & "Remove from favorite".

When I add the favorite, I change the ID of the DIV for remove. I can successfully add to favorite but I can't undo.

This code for add

    $('#addToFavoriteButton').click(function (event) {
        var ItemID = $('#addToFavoriteButton').data('itemid');
        event.preventDefault();
        $.post('/system/ajax.php', {
            AddFavID: ItemID 
        }, function (response) {
            document['getElementById']('addToFavorite').id = 'RemoveFavoriteButton';
        });
    });

This code for remove

$('#RemoveFavoriteButton').click(function (event) {
        var ItemID = $('#RemoveFavoriteButton').data('itemid');
        event.preventDefault();
        $.post('/system/ajax.php', {
            RemoveFavbidID: ItemID
        }, function (response) {
            document['getElementById']('RemoveFavoriteButton').id = 'addToFavoriteButton';
        });
    });

Where am I wrong?


Solution

  • The main problem with your code is that you are assigning an event handler to a button and then changing the ID of that button, expecting it to trigger different code when it is clicked. That is wrong.

    If you change the ID of an element it will still trigger the event handler that you originally assigned to it. See this example...

    $("#button1").on("click", function() {
      alert("you clicked button 1 - my id is " + this.id);
    });
    
    $("#button2").on("click", function() {
      alert("you clicked button 2");
    });
    
    // change the ID of #button1 to #button2
    $("#button1").attr("id", "button2");
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <button id="button1">button 1</button><br/>
    <button id="button2">button 2</button><br/>

    What makes more sense is to have a button to add a favourite, and a button to remove a favourite. You just hide the remove button until add is clicked, and vice-versa.

    Like this...

    var $add = $("#addFavourite");
    var $remove = $("#removeFavourite");
    
    $add.on("click", function() {
      $add.hide();
      $remove.show();
      
      var itemId = $add.data("item-id");
      alert("adding item " + itemId);
    
      // do your AJAX stuff to add the favourite here
      
    });
    
    $remove.on("click", function() {
      $add.show();
      $remove.hide();
      
      var itemId = $add.data("item-id");
      alert("removing item " + itemId);
    
      // do your AJAX stuff to remove the favourite here
      
    });
    #removeFavourite {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <button id="addFavourite" data-item-id="123">add favourite</button>
    <button id="removeFavourite" data-item-id="123">remove favourite</button>