Javascript Submitting Data to Form Twice

617 Views Asked by At

Lets say I have a simple form:

​<form id="new_stuff">
    <label>Title </label>
        <input id="title" maxlength="255" name="new[title]" size="50" type="text"><br /><br />
    <label>Message </label>
        <input id="message"  name="new[message]" size="50" type="text" value="general"><br />
    <label>Upload </label>
        <input id="upload_data" name="new[upload]" size="30" type="file"><br />
    <input id="submitform" action="form.php" type="button" value="submit me" formmethod="post"/>
​</form>

When a user fills the data in and hits submit, I need a way to get the data, alter the title (lets say add the word "TESTING" to the end of whatever the user entered) and then submit the form twice; once with the original data, another with the changed data.

Can anyone help me out with a method of doing this in JS. Thanks

1

There are 1 best solutions below

3
On

A little bit of jQuery makes this pretty easy.

$( "#new_stuff" ).submit( function () {
  var self = this;
  // Save the form data as-is, before making any changes
  var originalFormData = $( self ).serialize();

  // Make changes to the values that you want to change.
  $( "#title" ).val( $( "#title" ).val() + ' TESTING' );

  // Serialize the form a second time
  var modifiedFormData = $( self ).serialize();

  // Post the form to your location.
  $.post('url', originalFormData);
  $.post('url', modifiedFormData);

  // Return false, otherwise the form action will post (a third time).
  return false;
});