How to send this "dt" variable to Promise.done?

Asked

Viewed 28 times

0

I have the following javascript line:

...
var refundVal = $( ".refundVal" ).val();
var dt={ 
         orderId:orderId,
         refundVal:refundVal,
         process:btnProcess
        };

window.srObjc.confirm("message $"+refundVal+" ?").promise.done(function(dt) 
{
         console.log("test0");  //L1
         console.log(dt);       //L1
         console.log("test1");  //L1
         console.log(refundVal);//L4

         //Ajax
         var request =$.ajax({
                               url: "pagamentos.php",
                               type: "POST",
                               data: dt,
                               dataType: "json"
                              });

         request.done(function(dataset){  

                                  var resut = dataset;
                                  var str = JSON.stringify(resut, null, 2);
                                  alert(str);//test


                                  container.html(render(resut));
                                  $('#raw-data').html(syntaxHighlight(str));
                                  console.log(str);//test
                         }); 

}//window.srObjc.confirm

In this example the value refundVal is equal to $1.

this is the result in console.log: inserir a descrição da imagem aqui

The value of "dt" is showing "ok". I expected to see an object with the values in the doconsole log. And the value of refund val is correct =$1, and I wasn’t expecting this because I’m not sending this value in the function parameter promise.done(function(dt).

So the question is how do I send this object into the function and see the correct display in the console.log ?

  • dt is global in this code you showed. So if you do not declare (via function parameter) a dt new, it will be accessible. Strip dt from here: promise.done(function(dt)

1 answer

0


What happens is that by adding dt in the callback function of the Promise, here on this line:

window.srObjc.confirm("message $"+refundVal+" ?").promise.done(function(dt)

you end up creating a new variable in the function scope, but with the same variable name dt that is in the global scope, in this part of the code:

var dt={ 
     orderId:orderId,
     refundVal:refundVal,
     process:btnProcess
    };

If you remove the callback function variable, or by changing its name, you will get the desired result.

To better understand the scope I suggest this article which explains well how the variable scope works.

Browser other questions tagged

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