Javascript with ajax, function return. Why doesn’t it work?

Asked

Viewed 650 times

3

I made a code Javascript to enable some buttons and inputs in a FORM, according to the user’s permission, stored in a SESSION. 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 function PHP ./functions/processMaxDescAcresc.php correctly returns the user level check. But despite the function verUserPermissions, return true, did not enable buttons and inputs in the function showEditButtons.

If I move the function code showEditButtons into the other function, in this case eliminating the function showEditButton, It works, it works like this:

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 doesn’t it work? I don’t know much about Javascript and ajax, but in my opinion, it should work.

1 answer

5


This happens due to "racing conditions", since ajax is by default the calls of Ajax do not stop a script;
that is to say:

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 function Z and if it returns truth, make the party". However, the Z function has an Ajax call that has the Success and fail function (translating this to mean "Go there and fetch something, and when you come back with the answer, use one of the functions".

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

The reverse happens when you pass the code to the function that is called afterward of the answer to arrive.

  • Good... very good to know, sometimes some details of some languages end up getting in the way.

  • uma vez que ajax é, por defeito, asincrono ?? defect?

  • @Danielomine was literally translated, I wanted to say padrão. Good point :)

  • translate "default" as "default" is something very distinct..

  • @Danielomine happens when I don’t translate what I think, like "donate" instead of "donate" (Donate); it’s one of those stupid flaws :)

  • I understand, but it has nothing to do with these justifications.

Show 1 more comment

Browser other questions tagged

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