Enable Submit Button after CSRF Token Is Obtained

Introduction

When there is slow network connectivity between the client and the Joget server, users might encounter errors if they attempt to submit a form before the CSRF (Cross-Site Request Forgery) token is obtained. This issue can lead to a frustrating experience, resulting in an error page. To prevent this, you can implement a custom JavaScript solution that disables the submit button until the CSRF token is retrieved.

How does it work?

The provided JavaScript code monitors the presence of the CSRF token on the form. It disables the submit button initially and only enables it once the CSRF token is available. This approach ensures the form submission process is secure and prevents users from encountering errors due to missing tokens.

Here’s a breakdown of the script:

  1. Initially, the script disables the submit button to prevent premature form submission.
  2. The script checks whether the CSRF token has been generated by looking for the hidden input field containing the token.
  3. Once the CSRF token is found, the submit button is enabled, allowing the user to submit the form safely.
  4. If the token is unavailable, the script checks at regular intervals (every second) until the token is obtained.

The script is designed to be added to the userview builder's Custom JavaScript section.

function checkCSRFEnableSubmit(){
    //check for csrf token before enabling form submit button
    csrfValue = $("input[type=hidden][name=OWASP_CSRFTOKEN]").size();   
    if(csrfValue > 0){
        //enable button
        $("input[type=submit]").prop("disabled",false);
    }else{
        //check again in next cycle
        setTimeout("checkCSRFEnableSubmit()", 1000);
    }
}
 
$(function(){
 
if ( $("form").size() > 0){
    $("input[type=submit]").prop("disabled",true);
    checkCSRFEnableSubmit();
}
     
});
Created by Julieth Last modified by Aadrian on Dec 13, 2024