Changing the status of a checkbox component in the database using AJAX

Asked

Viewed 481 times

1

very good evening to all!

Well, I have a table in which there is a checkbox component. This component has the task of enabling and disabling a destination on my website. The figure below shows a table row with such an element:

inserir a descrição da imagem aqui

Here is the html code, it checks only if it is coming true or false from the database to render on the screen:

<c:forEach items="${destination}" var="d">
   <tr>
      <td>${d.dtName}</td>
      <td>${d.categories.ctName}</td>
      <td>
         <div class="make-switch" data-on="primary" data-off="info">
            <c:choose>
               <c:when test="${d.dtAppearWebsite}">
                  <input type="checkbox" checked>
               </c:when>
               <c:otherwise>
                  <input type="checkbox">
               </c:otherwise>
            </c:choose>
         </div>
      </td>
   </tr>
</c:forEach>

Well, my question is how could I change the state of my component via AJAX and reflect in the database. The bigger doubt is how I’m going to take such a component and make the asynchronous shape change.

Someone there has done something similar and can give me a strength?

Thank you for your attention

1 answer

2


To make the change in the bank, you need to have an action that does this. Let’s consider that there are 2 actions, a ativarDestino and the desativarDestino. When the checkbox is selected we will call to activate, otherwise we call the other.

$(document).ready(function() {

    // usando id para identificar o checkbox
    $('#myCheckbox').click(function() {
        var action = $(this).is(':checked') ? 'ativarDestino' : 'desativarDestino';

        // uma vez determinada a action, é só usar o get do jQuery
        $.get(action, function(data) {
            // faz alguma coisa com o retorno, manda msg de sucesso, algo assim
        })
        .fail(function(error) {
            // se der problema cai aqui. Você pode exibir o erro e desfazer a checagem do checkbox
        });
    });
});

You can see jQuery.get documentation here: http://api.jquery.com/jquery.get/

  • Hi Juliano all jewelry? Thanks for the help, but when it comes to the HTML component how can I do? Because currently I have a "when" that checks it for me. But I don’t know how I can do using the JS method you gave me. Could you help me? A hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.