Accessing function variable outside the function

I have a script tag inside which im doing a jQuery post request to a particular route,As shown below:

       <script type="text/javascript">
          const price=<%- JSON.stringify(parseInt(router.price)) %>
          $.post("/router/payment",{"price":price},function(data){
             respdata=data
          })
       </script>

The route which the $.post is refrencing to is this:

        router.post('/router/payment', function(req, res) {
        const RazorpayConfig = {
            key_id: 'rzp_test_wZvgiL1dZCBqcW',
            key_secret: 'W7l315GSK0JgZPXqSeWL8Rdv'
        };
        const price = req.body.price + '00';
        var instance = new Razorpay(RazorpayConfig);
    
        var options = {
            amount: price, // amount in the smallest currency unit
            currency: 'INR',
            receipt: 'order_rcptid_11',
            payment_capture: '0'
        };
        instance.orders.create(options, function(err, order) {
            res.json(order);
        });
    });

The context here is that im trying to integrate a payment portal into my webiste.The “respdata”,contains the order id which i am in need to initiate the payment.But im not able to access it outside the $.post.
I came accross “window”.I did somethind like this

window.respdata=data;

Even then i was not able to access it outside the $.post function.I also tried to declare the variable without any ‘var’ or ‘const’.Even then i failed.Any help regarding how to access it outside the $.post function,is really appriciated thanks.

$.post("/router/payment",{"price":price},callback)

function callback(data) {
  //do something with data
}

You could write your own ajax function using promises or async await to get the value back as a promise.

As a poor alternative, you could copy the content of your returned data to a hidden element in the DOM and retrieve it from there.

But there doesn’t seem to be a reason for doing either alternative. You should use the variable in place unless there’s a compelling reason you have to get it out of the function into the global space.