Here you are going to learn how to submit multiple html form from single page using jquery and ajax, This problem arise every phase of development If you are working on a rich application, Then you need to create multiple forms on single page and have to submit to server.
So in this topic i’ll tell you how to do this in better and simpler manner. It does not matter how many form on same page by this code you can handle all your form using single jquery script.
In this script i used some advance jquery function like closest(), serialize()
Read more about these function from jquery official website
closest: https://api.jquery.com/closest/
serialize: https://api.jquery.com/serialize/
Lets start the tutorial.
Create a simple html file and write down some sample html code
index.html
doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Submit multiple form using jquery and ajaxtitle>
head>
<body>
<h3>Submit multiple form using jquery and ajaxh3>
<div >
<b>Form-1b>
<form id="form1">
<table border=1><tr><td height=100><ul class="msgBox">ul>td>tr>
<tr><td>
<input type="hidden" name="fname" value="form1">
<input type="text" name="name" placeholder="Enter Name" required="required">
<input type="text" name="msg" placeholder="Enter Msg" required="required">
<button type="button">Submitbutton>
td>tr>table>form>
div>
<br/>
<div >
<b>Form-2b>
<form id="form2">
<table border=1><tr><td height=100><ul class="msgBox">ul>td>tr>
<tr><td>
<input type="hidden" name="fname" value="form2">
<input type="text" name="name" placeholder="Enter Name" required="required">
<input type="text" name="msg" placeholder="Enter Msg" required="required">
<button type="button">Submitbutton>
td>tr>table>form>
div>
<script src="http://code.jquery.com/jquery-1.10.2.js">script>
<script>
$(function() {
$("button").click(function() {
var formID = $(this).closest('form').attr('id');
var formData = $("#"+formID).serialize();
if($("#"+formID)[0].checkValidity()) {
$.ajax({
url: "request.php",
dataType: "json",
data: formData,
success: function( data ) {
// Handle success here
if(data.fname == 'form1') {
$("#"+formID+" .msgBox").append("
|
Submit multiple form using jquery and ajax
The above html code i have created two form form1,form2 you can create more form as per your need,
Where i assigned hidden input value fname for each form by this you can easily identify every form on server that which has been clicked.
Create your server file to handle your form request on server.
request.php
$formData = $_REQUEST;
if($formData['fname'] == 'form1') {
// do action for form1
echo json_encode($formData);
} else if($formData['fname'] == 'form2') {
// do action for form2
echo json_encode($formData);
}
?>
|
I hope this tutorial will help you to submit multiple form from single page.
If you like this post please don’t forget to subscribe my public note book for more useful stuff