I'm sure I'm overlooking something here... I have some jQuery code that fires off when a form button is pressed. The button is pressed, a coupon code is looked up and written in a div on the form and then the discount is applied (total = price - discount). Problem is, when I step thru Firebug to debug it, about 80% of the time the code works. However, when I run the code, it doesn't work. It's like the code runs too fast for the variables to get the correct information. Here's the code:
$('#coupon-submit').click(function() {
applyCoupon($('#coupon'), $(this));
var price = $('#price-total').text();
price = price.substring(5,price.length);
var theText = $('#fulldiscounttext').text(); // Sometimes this has a value while debugging, sometimes not
var discount = theText.substring(1, theText.length-4); // Takes unwanted characters out of string
var total = price - discount;
$('#price-total').text('US $ ' + total.toFixed(2));
var thetotal = $('#price-total').text();
$('#grandtotal').val(thetotal);
});
applyCoupon() looks up the code and writes it into the div #fulldiscounttext. I'm trying to have the #price-total div update with the discounted amount. It's not updating (unless I'm debugging it).
The applyCoupon() function:
function applyCoupon(couponInput, couponButton)
{
removeInputNames();
$.ajax({
data: $('#orderform').serialize(),
type: 'POST',
timeout: 5000,
url: 'coupon.php',
dataType: 'text',
beforeSend: function(request)
{
$('#coupon-error').text('');
couponButton.attr('disabled', 'disabled');
},
success: function(data, textStatus)
{
couponButton.removeAttr('disabled');
if(data == "bad error code")
couponOK = 0;
else
couponOK = 1;
if (!couponOK)
{
var badcode = couponInput.val().toString();
if (badcode.length > 0)
{
var fmt = 'You\'ve entered an invalid code.';
$('#coupon-error').text(fmt);
}
}
else // Coupon recognized!
{
$('#total-row').before('<tr><td colspan="4">'
+ '<div id="fulldiscounttext">' + data
+ ' Off</div>'
+ '</td></tr>');
// New discount information; save and update totals
$('#discount-storage').text(data);
showPrice();
}
}
});
}
applyCouponfunction - it's probably an async call...applyCouponcode?