JavaScript submit the form with parameters | Example code

  • by

You have to use jQuery to submit the form with parameters in JavaScript code.

<!-- jQuery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

//Code
$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});

JavaScript submit the form with parameters example

Simple HTML example code POST parameters before sending to the server.

  <html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script type="text/javascript">
      var params = [
      {
       name: "url",
       value: window.location.pathname
     },
     {
      name: "time",
      value: new Date().getTime()
    }
    ];

      $('#commentForm').submit(function(){ //listen for submit event
        $.each(params, function(i,param){
          $('<input />').attr('type', 'hidden')
          .attr('name', param.name)
          .attr('value', param.value)
          .appendTo('#commentForm');
        });

        return true;
      }); 
    </script>
  </head>

  <body>

    <form id="commentForm" method="POST" action="api/comment">
      <input type="text" name="name" title="Your name"/>
      <textarea name="comment" title="Enter a comment"></textarea>
      <input type="submit" value="Post"/>
      <input type="reset" value="Reset"/>
    </form>
  </body>
  </html>

Output:

JavaScript submit the form with parameters

If you want to add parameters without modifying the form, you have to serialize the form, add your parameters and send it with AJAX:

var formData = $("#commentForm").serializeArray();
formData.push({name: "url", value: window.location.pathname});
formData.push({name: "time", value: new Date().getTime()});

$.post("api/comment", formData, function(data) {
  // request has finished, check for errors
  // and then for example redirect to another page
});

Source: stackoverflow.com

See .serializeArray() and $.post() documentation.

Do comment if you have any doubts or suggestions on this JS submit form topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.