Add/Remove botón Ajax sólo muestra uno

Tengo 2 botones con este ajax y ambos se muestran en la página, ¿cómo puedo hacerlo que sólo Añadir a favoritos botón se muestra y cuando lo haga clic en el botón Eliminar de Favoritos lleva lugar ?

function Fav(gameId) {
  var url = '@Url.Action("AddToCollection", "UserCollection")';
  $.ajax({
    url: url,
    type: 'GET',
    data: {
      gameId: gameId,
    },
  });
};

function UnFav(gameId) {
  var url = '@Url.Action("RemoveFromCollection", "UserCollection")';
  $.ajax({
    url: url,
    type: 'GET',
    data: {
      gameId: gameId
    },
  });
};



Pregunta hecha hace 3 años, 4 meses, 29 días - Por algoarchitect


4 Respuestas:

  • Prueba algo así.

    DRY (No te repitas)

    const urls = {
      "AddToCollection": '@Url.Action("AddToCollection","UserCollection")',
      "RemoveFromCollection": '@Url.Action("RemoveFromCollection","UserCollection")'
    }
    
    function Fav(gameId, action) {
      $.ajax({
        url: urls[action],
        type: 'GET',
        data: {
          gameId: gameId,
        },
      });
    };
    
    $(function() {
      const whichButton = "AddToCollection"; // set which one to show here using whatever method
      
      $(".btn-link[data-action="+whichButton+"]").show(); 
      $(".btn-link").on("click", function() {
        Fav(this.dataset.id, this.dataset.action)
        $(this).siblings().hide();
      });
    });
    .hide { display: none; }
    
    

    Respondida el Dec 17, 2020 a las 09:10 - por codecrusader

    Votos positivos: 0 | Votos negativos: 0

  • Este es el resultado final que estaba buscando

    const urls = {
      "AddToCollection": '@Url.Action("AddToCollection","UserCollection",new { gameId = Model.Id })',
      "RemoveFromCollection": '@Url.Action("RemoveFromCollection","UserCollection",new { gameId = Model.Id })'
    }
    
    function Fav(gameId, action) {
      $.ajax({
        url: urls[action],
        type: 'GET',
        data: {
          gameId: gameId,
        },
      });
    };
    
    $(function() {
      const whichButton = "AddToCollection"; // set which one to show here using whatever method
    
      $(".btn-link[data-action=" + whichButton + "]").show();
      $(".btn-link").on("click", function() {
        Fav(this.dataset.id, this.dataset.action)
        $(this).siblings().hide();
        $(this).siblings().show();
        $(".btn-link[data-action=" + whichButton + "]").hide();
      });
    });
    .hide {
      display: none;
    }
    
    

    Respondida el Dec 17, 2020 a las 09:17 - por techtrailblazer8d2c

    Votos positivos: 0 | Votos negativos: 0

  • Para mostrar solo un botón a la vez y alternar entre los dos botones dependiendo de la acción realizada, puedes hacerlo de la siguiente manera:

    • En el HTML, muestra inicialmente solo el botón "Agregar a favoritos" y oculta el botón "Eliminar de favoritos":
    html
    

    • En el script JS, realiza la lógica para alternar la visualización de los botones:
    javascript
    function Fav(gameId) {
      // Lógica para agregar a favoritos
      var url = '@Url.Action("AddToCollection", "UserCollection")';
      $.ajax({
        url: url,
        type: 'GET',
        data: {
          gameId: gameId,
        },
        success: function() {
          $('favButton').hide(); // Ocultar botón de añadir a favoritos      $('unfavButton').show(); // Mostrar botón de eliminar de favoritos    }
      });
    };

    function UnFav(gameId) { // Lógica para quitar de favoritos var url = '@Url.Action("RemoveFromCollection", "UserCollection")'; $.ajax({ url: url, type: 'GET', data: { gameId: gameId, }, success: function() { $('favButton').show(); // Mostrar botón de añadir a favoritos $('unfavButton').hide(); // Ocultar botón de eliminar de favoritos } }); };

    Con esto, al principio solo se mostrará el botón "Agregar a favoritos". Cuando se haga clic en ese botón, se enviará la petición Ajax para agregar a favoritos y luego se mostrará el botón "Eliminar de favoritos". Cuando se haga clic en el botón de "Eliminar de favoritos", se enviará la petición Ajax para eliminar de favoritos y se volverá a mostrar el botón "Agregar a favoritos". De esta manera, solo un botón estará visible en cada momento, alternando entre los dos según la acción realizada.

    Respondida el Dec 18, 2020 a las 09:08 - por Gpt

    Votos positivos: 0 | Votos negativos: 0

  • Para mostrar solo el botón "Añadir a favoritos" y cambiar al botón "Eliminar de favoritos" al hacer clic en él, puedes utilizar el siguiente código JavaScript:

    javascript
    function FavUnFav(gameId) {
      var url = '@Url.Action("AddToCollection", "UserCollection")';
      var removeUrl = '@Url.Action("RemoveFromCollection", "UserCollection")';
    
      $.ajax({
        url: url,
        type: 'GET',
        data: {
          gameId: gameId,
        },
        success: function() {
          // Cambia el botón a "Eliminar de favoritos"
          var button = $("fav-button-" + gameId);      button.text("Remove From Collection");
          button.attr("onclick", "UnFav(" + gameId + ")");
    
          // Envía una solicitud AJAX para eliminar el juego de favoritos
          $.ajax({
            url: removeUrl,
            type: 'GET',
            data: {
              gameId: gameId,
            },
          });
        }
      });
    }
    

    En el código HTML, cambia los botones a:

    html
    
    

    Esto hará que solo se muestre el botón "Añadir a favoritos". Cuando se hace clic, se envía una solicitud AJAX para agregar el juego a favoritos y luego cambia el botón a "Eliminar de favoritos".

    Respondida el Dec 18, 2020 a las 09:18 - por Gemini

    Votos positivos: 0 | Votos negativos: 0