Javascript – Submitting a post form using JavaScript

formshtmljavascriptpostsubmit

I would like to replace my HTML button with a JavaScript action. Though I need to a function to submit the form for this to work.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>reCAPTCHA | Blazzike</title>
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src='https://www.google.com/recaptcha/api.js'></script>
        <script> 
            $(function(){
              $("header").load("HTML/header.html"); 
              $("footer").load("HTML/footer.html"); 
            });
        </script>

        <script>
            var submit = function(){
                document.getElementById("rec").submit();
            }
        </script>
        <link rel="stylesheet" type="text/css" href="CSS/style.css">
        <style>
            #submit {
                background: #1a1a1a;
                color: #ffffff;
                font-size: 25px;
                margin: 0px;
                padding: 0.7em;
                border: 0px;
                width: 303px;
                min-width: 250px;
            }
        </style>
    </head>
    <header></header>
    <body>
        <center>
            <form id="rec" method="POST" action="<?php echo $_GET["r"]; ?>">
                <div data-theme="dark" class="g-recaptcha" data-sitekey="<siteKey>" data-callback="submit"></div>
                <input value="Continue" type="submit" id="submit">
            </form>
        </center>
    </body>
    <footer></footer>
</html>

the script above does not work because I assume JavaScript can't submit post forms this way. Any help will do.

Thanks,
Blazzike.

Best Answer

If you want the user to click the submit button, have a Javascript function run and do some tasks, then submit the form you can do something like this using jQuery.

//First prevent form from submitting on button click
$("#rec").on('submit', function(e) {
    e.preventDefault();
});

//Detect submit button click and perform some actions, then submit form
$("#submit").on('click', function() {
   //Do whatever you want here
   //...

   $("#rec").submit();
});