I’m creating a custom module and I want to be able to submit the form via Magento’s built-in AJAX. Also, I want to validate the user input to ensure I don’t get a database full of blanks!

Magento makes hooking into the existing functionality really quite easy. Let’s begin with the form.

The Form

[php toolbar=”true” classname=”one_line”] <form class="my-form" name="myForm" id="myForm">

<label>
<span>First Name:</span><span>*</span><br />
<input class="required-entry" type="text" name="first_name" id="first_name" />
</label>
<label>
<span>Last Name:</span><span>*</span><br />
<input class="required-entry" type="text" name="last_name" id="last_name" />
</label>

more fields here

<input type="submit" value="enter" />
<span id="formLoader" style="display:none;">&nbsp;</span>
</form>
<div id="formSuccess" style="display:none;">&nbsp;</div>
[/php]

That’s it, honest. You could put action and method tags in if you like, but it’s not necessary. This form belongs in your .phtml file, along with the following code.

The Javascript

[code lang=”js” classname=”one_line”] <script type="text/javascript">
//<![CDATA[
var formId = ‘myForm’;
var myForm = new VarienForm(formId, true);
var postUrl = ‘<?php echo $this->getUrl("namespace_module/method/action") ?>’;
function doAjax() {
if (myForm.validator.validate()) {
new Ajax.Updater(
{ success:’formSuccess’ }, postUrl, {
method:’post’,
asynchronous:true,
evalScripts:false,
onComplete:function(request, json) {
Element.hide(formId);
Element.show(‘formSuccess’);
},
onLoading:function(request, json){
Element.show(‘formLoader’);
},
parameters: $(formId).serialize(true),
}
);
}
}

new Event.observe(formId, ‘submit’, function(e){
e.stop();
doAjax();
});
//]]>
</script>
[/code]

This Javascript is relying on the prototype library, which comes in-built with Magento; no frills here.

And that is all there is to it. The form will be checked for the required fields and submit via POST asynchronously on successful validation.

One Comment

  1. July 8, 2018 at 1:35 am

    Thanks a lot for sharing this with all of us you really understand what you
    are speaking approximately! Bookmarked. Please
    also discuss with my web site =). We can have a hyperlink alternate arrangement between us

Leave A Comment