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.
});
});
});