Jquery applies css style only the last time it runs

Asked

Viewed 41 times

0

Hello.

I have a table with information that will be entered in the database, making a request line by line.

Exemplo de dados a serem cadastrados

Let’s take the image as an example:

If I want to register in the bank these 5 rows of the table, I need to press the button that will register one by one, returning a result of success (true) or failure (false) for each row in the table.

After the function is finished all lines are registered without any problem,

If the return is true, the respective line that has just been registered should receive a background style. And this is where I find my problem.

In the ai case of the image, all 5 rows of the table were successfully included in the database. However only the last line receives the style that should have been applied in all.

                        $.ajax({
                          url : "includes/bCadastros.php",
                          dataType: 'html',
                          type : 'post',
                          data : post,
                          beforeSend : function(){
                                // Adicionar progress bar
                          }
                        })
                         .done(function(msg){


                            */ A próxima condição (if/else) define o estilo 
                               que a linha da tabela vai ficar e parece 
                               funcionar apenas na última vez em que é 
                               requisitado  */

                             */ A variável *atual* serve como ponteiro para 
                                que se saiba qual linha acaba de ser 
                                registrada e receberá o estilo. Caso eu crie 
                                um alert(atual) nesse nível ele irá mostrar 
                                corretamente o ponteiro pra cada uma das 
                                linhas  */

                            if(msg == 'ok')
                            {

                              */ Mas se caso eu crie o mesmo alert(atual) 
                                 neste nível, nenhum alert será emitido e o 
                                 comportamento será semelhante ao da imagem  
                               */

                                $('#b'+atual).addClass('bCadastrado');
                                $('#b'+atual).removeClass('bFalha');
                            }
                            else
                            {
                                 $('#b'+atual).addClass('bFalha');
                                 $('#b'+atual).removeClass('bCadastrado');
                            }

                            console.log(msg);

                         })
                         .fail(function(jqXHR, textStatus, msg){
                              console.log(msg);
                         }); 

This request is requested for each row of the table, and works when it comes to accessing the external file and including the records. But when applying the style it presents flaw.

Does anyone know what could be causing this ?

Full function

$('#bCadastrarOs').on('click',function(){

     var campo = ['sap','n_os','valor','servico','contrato','tipo','juncao','data'];

        for(i = 0; i < incluidos.length; i++)
        {
            var k = 0;
            var atual = incluidos[i];
            post = '';

            //Função que monta a string com formato de envio que organiza as informações para serem cadastradas
            $('#b'+incluidos[i]).children('td').each(function(i){

                if(i == 0)
                 {
                     post = campo[k]+'='+$(this).html();
                 }
                 else
                 {
                     post = post+'&'+campo[k]+'='+$(this).html();
                 }

                    k++;

            });

            if(post != '')
                {

                    post = post+'&acao=os';

                    $.ajax({
                          url : "includes/bCadastros.php",
                          dataType: 'html',
                          type : 'post',
                          data : post,
                          beforeSend : function(){
                                // Adicionar progress bar
                          }
                        })
                         .done(function(msg){

                            if(msg == 'ok')
                            {
                                $('#b'+atual).addClass('bCadastrado');
                                $('#b'+atual).removeClass('bFalha');
                            }
                            else
                            {
                                 $('#b'+atual).addClass('bFalha');
                                 $('#b'+atual).removeClass('bCadastrado');
                            }

                            console.log(msg);



                         })
                         .fail(function(jqXHR, textStatus, msg){
                              console.log(msg);
                         }); 
                }
        }

  });
  • Put the rest of the code, the whole function.

  • That is the problem for with an AJAX inside. That’s not very good.

  • I also believe that it may be something complicated, but the main goal that is to register in the bank works perfectly. That’s why I’m so excited about this rsrs behavior. Of course there are other ways to show the user that the lines were registered, but I wanted to use this particular kkk #sad

  • 1

    It is because the for runs all at once, and AJAX is asynchronous... so the value of the variable atual will be the last lap of the for.

  • But if it worked that way, all the lines would turn green, except the last one. No ?

  • @Bsalvo, is happening exactly what @Sam said, as AJAX is asynchronous, the loop of for will end before callback functions are executed, thus the variable atual will always be the last value filled in it, which corresponds to the last index of the loop. Some solutions to your case would be you pass all the records in one post and then loop the results, or pass the post the item index and return it in the callback to use it.

Show 1 more comment

1 answer

0


Well, as discussed with our more experienced colleagues, FOR which encompassed the completed AJAX request to fulfill its function before all requests return the information required for the style application.

To get around the situation I withdrew the AJAX call from inside the FOR, now it just prepares the string to be added to the database and adds to an array called requisicoes[]

Right after that, I request AJAX and after it has been successful, I call the same function recursively until the whole array requisicoes[] be covered.

Follows the solution:

function bEnviarOs(requisicoes,vezes,incluidos)
  {

      console.log(requisicoes[vezes]);

      if(vezes >= 0)
      {
                        requisicoes[vezes] = requisicoes[vezes]+'&acao=os';

                        $.ajax({
                          url : "includes/bCadastros.php",
                          dataType: 'html',
                          type : 'post',
                          data : requisicoes[vezes],
                          beforeSend : function(){
                                // Adicionar progress bar
                          },
                          success: function(msg)
                          {
                              if(msg == 'ok')
                            {
                                $('#b'+incluidos[vezes]).addClass('bCadastrado');
                                $('#b'+incluidos[vezes]).removeClass('bFalha');
                            }
                            else
                            {
                                 $('#b'+incluidos[vezes]).addClass('bFalha');
                                 $('#b'+incluidos[vezes]).removeClass('bCadastrado');
                            }


                            bEnviarOs(requisicoes,vezes-1,incluidos);

                           console.log(msg);
                          }
                        })

                         .fail(function(jqXHR, textStatus, msg){
                              console.log(msg);
                         }); 
      }
  }

Browser other questions tagged

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