简体   繁体   中英

Two post destination in one script with form action tag blank?

here is simple form :

<form id="contactform" method="POST" action="" >
          <div class="form-group">
           <input type="text" class="form-control"  id='first_name' name='first_name' > 
           <button type="submit" class="btn btn-success btn-lg " name="form_subbmit">Send</button> 
</form>

And myscript for subbmit:

<script>


// Attach a submit handler to the form
$( "#contactform").submit(function( event ) {

 var $form = $( this );

 first_name=$form.find( "input[name='first_name']" ).val();


 $.post( "http://post1.com", { first_name: first_name  } );
 $.post( "http://post2.com", {first_name: first_name  } );

});
</script>

Now, if I put one of two post destination in action of form,all is fine. If take code like this,no submit at all.

How can I sent data to post destinations and take action filed of form to be blank ?

Tnx

Try this code:

<script>
   function submitWithPost(){
      var $form = $( this );

 first_name=$form.find( "input[name='first_name']" ).val();


 $.post( "http://post1.com", { first_name: first_name  } );
 $.post( "http://post2.com", {first_name: first_name  } );

   }
</script>

<form onsubmit="return submitWithPost();" >

First put the event prevent default:

$("#contactform").submit(function( event ) {
    event.preventDefault();
    ...
});

On done you have to clean the input text field like this:

$.post( "http://post1.com", { first_name: first_name })
      .done(function(data) { 
         $form.find("input[name='first_name']").val('');
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM