How to update a row in the table with ajax?

Asked

Viewed 603 times

1

The idea is to click the valid or invalid button and update that line in the table, changing the class of the button to the respective situation class: valido or class: invalido with ajax.

My difficulty is how to handle data from response on and update the HTML .

Script

$.ajax({
  url: "updateTelefone.php
  type: 'get',
  dataType: 'json',
  data: {

  },
  success: function(response) {

  }


}


});

HTML

<table class="table">
  <thead>
    <tr>
      <th>codigo</th>
      <th>descricao</th>
      <th>Ação</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td>01</td>
      <td>11 5589-0000</td>
      <td>
        <button id="valido" class="sem-validacao">Válido</button>
        <button id="invalido" class="sem-validacao">Inválido</button>
      </td>
    </tr>
  </tbody>
</table>

2 answers

3

The sponse will bring the return data from the get at the url updateTelefone.php, as I saw that the dataType: is json then the return will come in this format.

When the request happens without errors it will call as callback the function you pass on Success, if you want to have the callback in case of error, you must add a function to the property error.

To further detail the answer I would need to know how the return would be, but I’ll put an example here.

ex: Let’s assume that the return would be {OK:true} for the case of valid and {OK:false} for invalid.

if(response.OK) {
     $("#valido").show();
     $("#invalido").hide();
}
else {
     $("#valido").hide();
     $("#invalido").show();
}

Edit 1:

if you want to update all table data you could do so:

success: function(response) {
    var html = '';

    for(var index in response) {
        html += '<tr>'
                   +'<td>'+response[index].ID+'</td>'
                   +'<td>'+response[index].DESCRICAO+'</td>'
                   +'<td>'
                        +(response[index].VALIDO ? 
                          '<button id="valido" class="sem-validacao">Válido</button>'
                        :
                        'button id="invalido" class="sem-validacao">Inválido</button>')
                  +'</td>'
              +'</tr>'
    }  

   $('tabela tbody').html(html);
}
  • Thanks for the explanation, but in case my difficulty is exactly to take the Answer and recreate the table in html with the updated data and lines with their respective classes valido invalido

  • Do you want to update all rows of the table or just the row you are clicking? What would be the return of the 'updateTelefone.php' url'?

  • The query returned would be all phones with ID, Descricao and the button with the class valido or invalido. Valid being green and invalid red.

  • I don’t know if ajax updates only one line, so I think you will have to return the complete query of that client and with javascript render the table with the data of the Response.

  • I edited to update the whole table, considering the data you said.

  • I’ll test it and I’ll tell you tomorrow, thank you very much

  • Friend, thank you so much for your effort in helping me, but the idea of the colleague above solved my problem. I am very grateful for your help.

Show 2 more comments

2


From what I understand, you just want to change the class of the button clicked after the return of AJAX, so you don’t need to receive any feedback response. The only thing you need to send in AJAX is the id row (which I assume is the column código table, which is the first td.) and information whether it is "valid" or "invalid".

First you shouldn’t put id="valido" and id="invalido" on the buttons, because you would have to repeat these id's on the other buttons of the other lines, and repeat id is incorrect in HTML. So do not use them. Instead, add a class only in the "Valid" buttons to differentiate from the "Invalid" buttons. I put the class .val, being like this:

                ↓
<button class="val sem-validacao">Válido</button>
<button class="sem-validacao">Inválido</button>

As you will not need any data returned from AJAX, you do not need to put response in the function of success, and also doesn’t need the option dataType: 'json',. You don’t have to put type: 'get',, for the type of $.ajax already is get by default.

Just then, after the AJAX is completed (function of the success) check if the clicked button has the class .val, to insert the class .valido or .invalido.

The code will look like this (see explanatory comments):

// pega o click nos botões pela classe .sem-validacao
$(".sem-validacao").on("click", function(){

   var $this = $(this); // variável para guardar o botão clicado

   // variável que irá ser "true" se o botão clicado tiver a classe .val
   // ou "false" se não tiver
   var valido = $this.hasClass("val");

   $.ajax({
      url: "updateTelefone.php",
      data: {
         id: $this         // botão clicado
            .closest("tr") // pega a linha do botão
            .find("td")    // busca uma coluna
            .first()       // a primeira coluna
            .text()        // pega o texto da coluna
            .trim(),       // remove espaços

         v: valido         // envia "true" ou "false"
      },
      success: function(){
         $this // botão clicado
         .addClass( valido ? "valido" : "invalido" ); // adiciona uma das classes
      }
   });
});

Note that AJAX sends two variables to PHP: id and v (these variables you can name as you like). In PHP you will get both with $_GET['id'] and $_GET['v'].

The $_GET['id'] will be the id of the telephone, and the $_GET['v'] will be true or false, you will need as information to update the database.

  • Sam, I really appreciate the tip. I adjusted your code to my need and it worked.

Browser other questions tagged

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