Today I am sharing an important article “How to submit multiple forms with jQuery and Ajax”. Just think What be happen if the scenario include multiple forms and it should use the same jquery ajax submission part.
Have you faced the problem how you can submit multiple forms by using the jQuery ajax? We’ll I did, I’ve encountered this recently during developing a web application.
I have added two forms in below html example.
1 2 3 4 5 6 7 8 9 10 11 12 |
<script type="text/javascript" src="jquery.js"></script> <form name="contact1" action="contact.php" method="POST" id="contact1"> <div>Name: <input type="text" name="name" id="name" required /></div> <div>Email: <input type="email" name="email" id="email" required /></div> <div><input type="submit" name="submit" value="Submit" /></div> </form> <form name="contact2" action="contact.php" method="POST" id="contact2"> <div>Name: <input type="text" name="name" required /></div> <div>Message: <input type="text" name="message" required /></div> <div><input type="submit" name="submit" value="Submit" /></div> </form> <div id="results"></div> |
Add below jQuery snippets before head tag closed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<script type="text/javascript"> $(document).ready(function() { $("form").submit(function() { // Getting the form ID var formID = $(this).attr('id'); var formDetails = $('#'+formID); $.ajax({ type: "POST", url: 'contact.php', data: formDetails.serialize(), success: function (data) { // Inserting html into the result div $('#results').html(data); }, error: function(jqXHR, text, error){ // Displaying if there are any errors $('#result').html(error); } }); return false; }); }); </script> |
1 2 3 4 5 6 7 8 9 10 |
<?php if(isset($_POST['email'])){ echo "Contact Form 1 Submitted Successfully"; } elseif (isset($_POST['message'])){ echo "Contact Form 2 Submitted Successfully"; } ?> |
I hope this article will help you. If you like this article, do like & share it with your friends on social media. Don’t forget to follow us on Facebook and Twitter to learn cool tutorials.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: Ajax, CSS, form multiple submit buttons, HTML 5, html form multiple submit, html form multiple submit buttons, html form with multiple submit buttons, javascript submit multiple forms, jquery submit multiple forms, multiple form submit, multiple submit buttons in a single form, php form multiple submit, Technology, Tip and tricks