update list field without refresh ajax

Asked

Viewed 1,201 times

-3

I have the following jsp list where I just want to increment the value of the quantity field without refreshing the page.

The way I did, it works, but updates the page. So I searched, it would have to be by Ajax.

<table>
   <tbody>
      <c:forEach items="${revistas}" var="r">
      <tr>
         <td>${r.nome }</td>
         <td>
            <form id="testeForm" action="<c:url value="/atualizaQuantidade"/>" method="post" >
               <input type="hidden" name="r.cod" id="cod" value="${r.cod}" />
               <input type="hidden" name="r.qtd" id="qtd" value="${l.qtd}" />
               <button type="submit" class="btn btn-primary">${r.qtd}</button>
            </form>
         </td>
      </tr>
      </c:forEach>
   </tbody>
</table>

Since it’s a list, I have to get the id of magazine, the amount in the list and send to my Java method to increment (this part I know how to do). Now do this via Ajax, I’m lost. Could you help me?

  • Where is the magazine ID?

  • The magazine ID value gets through ${r. Cod}

  • @Amandarj put an example, with the parameters of the form, if other, just inform.

1 answer

1


I believe you should exchange the tag form for an ajax method, next to a button click event

Remove this stretch:

     <td>
        <form id="testeForm" action="<c:url value="/atualizaQuantidade"/>" method="post" >
           <input type="hidden" name="r.cod" id="cod" value="${r.cod}" />
           <input type="hidden" name="r.qtd" id="qtd" value="${l.qtd}" />
           <button type="submit" class="btn btn-primary">${r.qtd}</button>
        </form>
     </td>

Add this:

  <td>
      <button data-cod="${r.cod}" data-qtd="${r.qtd}" class="btn btn-primary btn-qtd-click">${r.qtd}</button>
 </td>

Finally the following js, using jQuery:

$(".btn-qtd-click).click(function(){ //Click no botão
    var $this = $(this); //Referência do botão que foi clicado

    $.ajax({
       type: "POST",
       url: "/atualizaQuantidade", //Url do serviço POST
       data: {//Valores que o serviço recebe
          cod: $this.attr("data-cod"), //Usando atributo adicionado no html
          qtd: $this.attr("data-qtd"),
       },
      //dataType: dataType 
    }).done(function(){
        //FAca algo aqui se ocorrer tudo certo

        //Exemplo, atualizando o valor informado no button
        //$this.html(Nova quantidade)

    }).fail(function(){
         //Faça algo caso falhe
    })
 });

Browser other questions tagged

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