Using Magento’s Built-In AJAX Submit With Validation

back to tech articles
Magento 1.7.0.2 CE

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<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>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<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>

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.

Leave a Reply

Your email address will not be published. Required fields are marked *