I have a form where users are entering account numbers and I need to check that the entered account numbers are unique when the save button is clicked, but before form submission. This is on the magento backend and the ajax call is pointing to the function acctnumAction() in the indexController.
The number of account numbers is dynamic, there could be up to 5, but as few as 1, so I need to do an each loop on the items. I gave the account number fields their own class and loop over that.
This is what I’ve got.
function acctCheck(){
jQ.each(jQ(".acctnum"), function(x, y){
var acct = jQ(this).val();
var field = this;
jQ.get("'.Mage::helper('core/url')->getHomeUrl().'dealerlocator/index/acctnum", {acctnum: acct}, function(data){
var items = JSON.parse(data);
if(items != ""){
$(field).addClass("validation-failed");
return false;
}
});
});
}
function saveAndContinueEdit(){
if(acctCheck() !== false){ editForm.submit(); }
}
The save button onclick hits saveAndContinueEdit() and runs the function to check the account numbers.
I know this won’t work, the ajax will run asynchronously and return nothing before it could return false, and as long as it isn’t false, it submits. But I have tried wrapping the ajax call in $.when to no avail, i wrapped the if in saveAndContinueEdit() in a $.when, like so
function saveAndContinueEdit(){
jQ("#continueEdit").val("1");
jQ.when(acctCheck()).done(function(valid){
if(valid !== false){
editForm.submit();
}
});
}
but that didnt do the trick either, and is probably not even how it’s supposed to work, I was just trying whatever I could come up with.
The point of having it in the each is so that I could set a variable to false if an account number isnt valid, but still iterate through the rest so that the class will still be added to the fields if they are invalid, so the user will know, instead of fixing one then another pops up as invalid, even though my examples aren’t coded that way. I know the data that is returned by the get is valid, it just won’t run synchronously.
Anyone have any ideas?
I got it working using deferreds.
Returning the entire ajax (get) call acts as a deferred, i throw them all in an array and pass that to when(). So when all of the ajax calls complete, it hits then(), and voila.