Search code examples
javascriptjqueryforms

Adding POST parameters before submit


I've this simple form:

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

I need to add two POST parameters before send to the server:

var params = [
               {
                 name: "url",
                 value: window.location.pathname
               },
               {
                  name: "time",
                  value: new Date().getTime()
               }
             ];

without modifying the form, please.


Solution

  • To add that using Jquery:

    $('#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;
    });