Magento Ajax Form Submit – Fix Redirect to Controller Issue

ajaxform-validationformsrouter

I'm working on a newsletter signup form (following this tutorial). When I hit the signup button Magento redirects me to the "form action url" and displays the response on a white page only:

{"message":"
Thanks for signing up!
"}

I have no idea what is causing the issue.

My controller

class MyModule_Signupx_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        $this->loadLayout(array('default'));
        $this->renderLayout();
    }

    public function signupxAction()
    {
        $response = array();
        $response['message']="TEST";
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
    }
}

Javascript in template

<script type="text/javascript">
    //< ![CDATA[
    var customForm = new VarienForm('form-signupx');

        jQuery('#signupx').click(function (){
            var data = jQuery('#form-signupx').serialize();
            var url= "<?php echo $formActionUrl; ?>";
            console.log(data);
            if(customForm.validator.validate()){
                console.log("This does show up, just before the redirect happens");
                jQuery.ajax({
                          url: url,
                          dataType: 'json',
                          type : 'post',
                          data: data,
                          success: function(data){
                                console.log("This does not show up in console");
                          }
                    });
        }
    //]]>
</script>

config.xml

<frontend>
    <routers>
        <signupx>
            <use>standard</use>
                <args>
                    <module>MyModule_Signupx</module>
                    <frontName>signupx</frontName>
                </args>
        </signupx>
    </routers>

Thank you so much in advance!

Best Answer

I do not know your form but please make sure you submit the form with a button from type button and not submitting it by an input field:

<button id="xyz" title="Sign up" type="button"><span><span>Sign up</span></span></button>

Input won't work