Search code examples
javascriptjqueryformscsrfcsrf-protection

calling .trigger on javascript createElement


I am implementing a CSRF solution that automatically injects a token stored on the session into all forms before subitting them. I have implemented 2 solutions to ensure all submissions are handled

  1. For ajax submissions I have implemented a jquery.ajaxPreFilter method that adds the token to the data attributes before passing it through to the ajax handler.

  2. For other forms, I bind to the submit event using jquery.on('submit').

  3. For forms being submitted via javascript I have changed my .submit() calls to .trigger('submit');

There are some javascript methods in our code that will use javascript document.createElement() to create a form, before calling form.submit(). I am unable to change these to form.trigger('submit') as jquery does not recognise them; I get error "form.trigger is not a function".

How can I handle these types of form submissions to trigger the submit event so that my binding method will pick it up?


Solution

  • I have now found a solution, and didn't realise it was so simple.

    Instead of calling

    form.submit();
    

    I just call

    $(form).trigger('submit');