JavaScript with ajax, function return. Because it does not work?

3

I made a JavaScript code to enable some buttons and inputs in a FORM, according to the user's permission, stored in a SESSION. It had done so:

function showEditButtons() 
{
   if ( verUserPermissions(8) === true )
   {
      btnConfirma.style.display = 'inline';
      btnCancela.style.display = 'inline';
      btnEdita.style.display = 'none';
      $('input.form-control:text').attr("disabled", false);
   }
}

function verUserPermissions(nivel){
   $.ajax({
       url: './funcoes/processaMaxDescAcresc.php',
       type: 'POST',
       data: {'OP':'NIVEL', 'NIVEL_ESPERADO':nivel},
       cache: false,
       dataType: 'json',
       success: function(data, textStatus, jqXHR)
       {
          var result = (data.nivel_permitido == '1');
          if ( ! result )
          {
             abreModaldeAviso('Falha', 'Usuário não autorizado a alterar estes valores.', 'alerta');
          }
          return result;

       },
       error: function(jqXHR, textStatus, errorThrown)
       {
          var result = false;
          abreModaldeAviso('Falha', 'Erro ao obter dados do usuario.', 'alerta');
          return result;
       }
   });
};

The PHP ./funcoes/processaMaxDescAcresc.php function correctly returns the user-level check. But although the ViewUserPermissions function returned true, it did not enable the buttons and inputs in the showEditButtons function.

If I move the code from the showEditButtons function into the other function, in this case deleting the showEditButton function, that works:

function showEditButtons() {
   verUserPermissions(8);
}

function verUserPermissions(nivel){
   $.ajax({
      ...
      success: function(data, textStatus, jqXHR)
      {
         var result = (data.nivel_permitido == '1');
         if ( ! result ){
            abreModaldeAviso('Falha', 'Usuário não autorizado a alterar estes valores.', 'alerta');
         } else {
            btnConfirma.style.display = 'inline';
            btnCancela.style.display = 'inline';
            btnEdita.style.display = 'none';
            $('input.form-control:text').attr("disabled", false);
         }
      },
      error: function(jqXHR, textStatus, errorThrown)
      {
         var result = false;
         abreModaldeAviso('Falha', 'Erro ao obter dados do usuario.', 'alerta');
         return result;
      }
   });
};

My question is, why does not it work? I do not know much about JavaScript and ajax, but I think it should work.

    
asked by anonymous 31.08.2015 / 17:07

1 answer

5

This happens because of "racing conditions", since ajax is, by default, asynchronous, Ajax calls do not stop a script;
that is:

function showEditButtons() 
{
   if ( verUserPermissions(8) === true )**
   {
      btnConfirma.style.display = 'inline';
      btnCancela.style.display = 'inline';
      btnEdita.style.display = 'none';
      $('input.form-control:text').attr("disabled", false);
   }
}

** here in this line, what this will do is: "call me the Z function and if it returns true, it makes the party". However, the Z function has an Ajax call that has the function success and fail (translating this means "Go there to fetch anything, and when you get back with the answer, use one of the functions."

Now, here is a problem: "when you come back with the answer". This means that verUserPermissions() does not return true; It performs a function that, after some time, performs yet another function and this yes - returns true or false.

The inverse happens when you pass the code to the function that is called after the response.

    
31.08.2015 / 17:15