0

I have following AJAX.

And what I need to do is to use the variable tax_rate outside of $.ajax call. My ajax call is working properly since the variable tax_rate shows proper value in [1], but the variable becomes useless in [2].

Am I doing something wrong with variable scope?

<script>
jQuery(document).ready(function($) {

    $(document).on('blur','#form',function() {

        var subsum = 0;
        var tax_rate = 0;
        var tax_amount = 0;

        $('.form-row').each(function() {

            // calculate sums and totals per each form-row
            subsum = Number( $(this).find('.unit').val() * $(this).find('.price').val() ).toFixed(2);
            $(this).find('.subsum').empty().val(subsum);

            // calculate tax amount
            var tax_id= $(this).find('.tax_code').val();
            var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';

            // call ajax to retrieve the tax rate
            $.ajax({
                url: ajaxurl,
                data:' action=get_tax_rate_by_id&tax_id='+tax_id,
                type:'GET',
                success:function(results) {
                    tax_rate = results;
                    alert( tax_rate ); // [1] Obviously, this one properly alerts tax rate.             
                }
            });

            alert( tax_rate ); // [2] This one always alerts 0.

        });

    });
});

Dongsan
  • 85
  • 11
  • _AJAX_ stands for __Asynchronous__ which means _not existing or occurring at the same time._. – Satpal Nov 26 '14 at 07:27

2 Answers2

1

You have to make your ajax call synchronously because the alert will get executed before completing your ajax request as JavaScript run asynchronously. Although it will make your code a little slow but you will be able to return tax_rate outside of ajax. You can use

async:false 

in your ajax options to do that.

Manish Jangir
  • 5,329
  • 4
  • 42
  • 75
  • So the chances are that [2] gets executed even before the ajax call is completed? I see. Thank you. Your suggestion to make it synchronous works, but the code became too slow. Any other advice? – Dongsan Nov 26 '14 at 07:36
  • That I've mentioned in the answer. Your code becomes slow in case of synchronous ajax calls. – Manish Jangir Nov 26 '14 at 08:36
0

What if you try:

            success:function(results) {
                return tax_rate = results;                           
            }
kapantzak
  • 11,610
  • 4
  • 39
  • 61