Search code examples
javascripthtmlangularjsplaid

How do you send html form data using the action attribute without redirecting to another page?


I'm using Angular and Plaid. I want to submit the following form, which posts the public_token to /authenticate using the 'action' attribute in the html form. How do I post the public_token to my server (/authenticate) without redirecting to a different page.

Step 2: Simple integration

Include the following markup (the and tags) in your site or web application:

-- A hidden input named public_token will be appended to this form once the user has completed the Link flow. Link will then submit the form, sending the public_token to your server. --

<form id="some-id" method="POST" action="/authenticate"></form>

<script
  src="https://cdn.plaid.com/link/stable/link-initialize.js"
  data-client-name="Client Name"
  data-form-id="some-id"
  data-key="test_key"
  data-product="auth"
  data-env="tartan">
</script>

The directions for this can be found here: https://plaid.com/docs/link/#step-1-get-your-public_key

No guidance is given on how to get the public_token from the form on the client side though it clearly states that it's safe to expose it on the client side.


Solution

  • you have to prevent the default action of the form: there are a couple ways to do it here are two with both jQuery and Vanilla JS:

    jQuery

    $('#form').submit(function (event) {
        event.preventDefault();
        window.history.back();
    });
    

    JS

    if (element.addEventListener) {
        element.addEventListener("submit", function(event) {
            event.preventDefault();
            window.history.back();
        }, true);
    }
    else {
        element.attachEvent('onsubmit', function(event){
            event.preventDefault();
            window.history.back();
        });
    }
    

    Angular You can pass the $event object to your method, and call $event.preventDefault() on it, so that the default event wont occur:

    <a href="#" ng-click="do($event)">Click</a>
    
    // then in your controller.do($event) method
    $event.preventDefault()