Assign returned Success value to a variable

Asked

Viewed 153 times

-2

I have the following requisition ajax where it returns the value in success:

function novasMensagens(Alerta) {

    var retorno = Alerta > 0 ? Alerta : "";

    $.ajax({
        type: 'GET',
        url : './fetchbusca',
        success : function(data) {
            console.log(data);
            var Alerta = data;
            console.log(Alerta);
        }
    });
}

Return: {"0":"1","Alerta":"1"}

Now the value that returns is {"Alerta":"1"} I have to assign it to the Alert that is within the return variable:

var retorno = Alerta > 0 ? Alerta : "";
  • @Sam What I intend to take is this value returned within the sucess and use it in another role, as I can?

  • @Sam understood, but I did it and I get the mistake Alerta is not defined. Function function novasMensagens(Alerta){ $.ajax({ type: 'GET', url : './fetchbusca', success : function(data) { var Alerta = data; var retorno = Alerta > 0 ? Alerta : ""; return retorno; } }); } document.getElementById("msgNumero").innerHTML = novasMensagens(Alerta );

  • When you perform document.getElementById("msgNumero").innerHTML = novasMensagens(Alerta ); Ajax has not yet been processed. Ajax is asynchronous.

  • @Sam means I have to put Javascript inside the header?

  • No. Everything that comes from Ajax you must do inside the Success function. That’s where the values are returned.

2 answers

0

In the form in which the reply was written, before any change is made, it is sufficient to carry out as follows:

function novasMensagens(Alerta){
  var retorno = Alerta > 0 ? Alerta : "";

  $.ajax({
      type: 'GET',
      url : './fetchbusca',
      success : function(data) {
          retorno = data.Alerta
      }
  });
}
  • doing conole.log(Alerta); before the ajax and returns undefined, and should return 1

  • Alerta before the request is Alerta defined as a method parameter, then it will have the value of before the request, in the success stay in line with the variable scope. I recommend using different names to better understand what happened.

  • Realize that Alerta is not within return, you just checked it and assigned the value, not the reference of Alerta, for apparently Alerta is an integer and not an object. To use the return value of ajax make your logic within Success.

0

What you are trying to do will not work because there is no way to recover the value of "Alert" out of ajax. Use the "Error" array of ajax

$.ajax({
          type: 'GET',
          url : './fetchbusca',
          success : function(data) {
              //exibe o alerta
          },
          error:function(){
              //faz algo se der erro
          }

      });

Browser other questions tagged

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