Octobercms - CSRF Protection On A Form To Preventing Multiple Submission

- 1 answer

I have a component with a form and then code to handle the submission. The problem is, if I spam the button it will submit the form multiple times. A solution to this would be to add a disabled state via Javascript to prevent the user from doing this.

From a security reason I do not want this to happen at all and prevent server side. I have a token and in the config I have CSRF enabled

'enableCsrfProtection' => true,

Here is my form

{{ form_open({ request: 'onSubmit' }) }}

            <div class="form-group">
                <label class="control-label" for="subject_name">Subject's name</label>
                <input id="subject_name" name="subject_name" type="text" placeholder="" class="form-control input-md" required="">


            <div class="form-group">
                <label class="control-label">Postcode</label>
                <input id="postcode"  name="postcode" class="form-control input-md" type="text" required>

            <div class="form-group">
                <button id="submit" type="submit" value="submit" class="btn btn-lg btn-gold pull-right"><i class="fa fa-lock"></i> Request Job</button>


and in the generated html

Handler/ Session / Token

<input name="_handler" type="hidden" value="onSubmit">
<input name="_session_key" type="hidden" value="7Eg9bK4pcT2NOgWwUS0UFUckjkSMRC1UDBkBhPwO">
<input name="_token" type="hidden" value="00nbkK3EAo2I8WGWSh85qkMjHYig6aldrd3oe8HZ">

Then in my components code

public function onSubmit()

    $name = post('subject_name');
    $postcode = post('postcode');

    if (Session::token() != Input::get('_token')) 

        /* Invalid token */ 
        return print('Token invalid');


    $job = new Job;
    $job = $job->name = $name;
    $job = $job->postcode = $postcode;


Yet I spam the submit button and it will execute multiple times. How can I add the ability to only execute once?



What you need is a loader

<div class="loading-indicator-container">

    <button id="submit" type="submit" value="submit" data-load-indicator="Saving..." class="btn btn-lg btn-gold pull-right"><i class="fa fa-lock"></i> Request Job</button>