I want the variable to be accessed from anywhere

0

Issue

Here i want to access the variable “finalPrice ” in another function, how can i achive this?

  function available(id){
    $.ajax({
        method:"GET",           
    }).done(function(data){        

     for(j=0; j<available_location.length; j++) {

            var finalPrice =available_location[j].price_details.final_price;
   };
});

function razorpay() {      
    $.ajax({
        url : 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
        type : 'GET',
        data : {

         },
        success: function(data){
              alert(finalPrice );
           }
    });
}

Solution

Your finalPrice is scoped only to the available function since that’s where it’s declared (var finalPrice). In Javascript, if you want a variable to be accessable from all script scopes, move it outside the function, to the beginning of the script:

var finalPrice;

function available(id) {
    $.ajax({
          method:"GET",           
    }).done(function(data) {        
       for(j = 0; j < available_location.length; j++) {
           finalPrice = available_location[j].price_details.final_price;
       };
});

function razorpay() {      
    $.ajax({
        url: 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
        type: 'GET',
        data: {
        },
        success: function(data){
           alert(finalPrice );
        }
    });
}

Answered By – Koby Douek

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More