I'm trying to modify some code in Magento to create a pair of AJAX calls such that the second call only activates if the first one succeeds. Specifically, I'm trying to insert some additional address validation code into the billing page on checkout, so that the stock Magento validation + form post (via AJAX) only happens if the address validates as a valid postal address.
My problem comes from trying to reference certain functions in the inner call, where I'm running into some namespace issues. Example code:
var Billing = Class.create();
Billing.prototype = {
initialize: function(form, addressUrl, saveUrl){
this.form = form;
if ($(this.form)) {
$(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
}
this.addressUrl = addressUrl;
this.saveUrl = saveUrl;
this.onAddressLoad = this.fillForm.bindAsEventListener(this);
this.onSave = this.nextStep.bindAsEventListener(this);
this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
},
save: function() {
//(initialize things for first call, e.g., URL to use):
var addressRequest = new Ajax.Request(url,
{
method: 'get',
onSuccess: function(response) {
// (do some things with the results...)
// (initialize things for second call, which was
// the stock Magento AJAX call to validate form fields
// and post the results to another Web page...)
var request = new Ajax.Request(
this.saveUrl, // no longer in scope
{
asynchronous: true,
method: 'post',
onComplete: this.onComplete, // also no longer in scope
onSuccess: this.onSave, // also no longer in scope
onFailure: checkout.ajaxFailure.bind(checkout), // "checkout" is a distinct object and remains in scope
parameters: Form.serialize(this.form) // this.form no longer in scope
}
);
}
}
},
fillForm: function(transport) { ... },
nextStep: function(transport) { ... },
resetLoadWaiting: function(transport) { ... },
The original "this.xxx" references such as this.form and this.onComplete are no longer in scope once they're in the nested call. I would like to know how to refer to them correctly at any nested depth (there are a couple of other AJAX calls I may want to make here as well). Any suggestions would be greatly appreciated!