Search code examples
jqueryajaxcsrfsap-commerce-cloud

How to add a hidden field to a form with ajaxForm before it goes to the server


I need to add a hidden field with its corresponding value to a form (for CSRF protection) whenever it is submitted with the JQuery method: ajaxForm. But I am just getting familiar with front-end and I am struggling to come up with the right javascript for this. Has anybody done that?


Solution

  • You may use beforeSerialize hook to inject the hidden field in the DOM like this:

    <form id="myForm" action="/myActionUrl" method="post">
        <input type="text" name="myTextBox" value="test" />
        <input id="submitBtn" type="button" onclick="submitThis(this)" value="Submit">
    </form>
    
    function submitThis(btnSubmit) {
        $('#' + btnSubmit.form.id).ajaxSubmit({
            dataType: 'json',
            beforeSubmit: onBeforeSubmit,
            beforeSerialize: onBeforeSerialize
        });
        return true;
    }
    
    function onBeforeSerialize($form, options) {
        if($('input:hidden[name=myHiddenField]').length == 0) {
            $('<input />').attr('type', 'hidden')
                .attr('name', "myHiddenField")
                .attr('value', "val")
                .appendTo('#myForm');
        }
    }
    
    function onBeforeSubmit(formData, jqForm, options) {    
        var queryString = $.param(formData);
        alert('Querystring: \n' + queryString + '\n');
        return true;
    }