WebToTell
How to post multiple forms with php and ajax - Printable Version

+- WebToTell (https://www.webtotell.com)
+-- Forum: PHP for beginners and advance users.PHP Code samples, applications. (https://www.webtotell.com/Forum-PHP-for-beginners-and-advance-users-PHP-Code-samples-applications)
+--- Forum: PHP (https://www.webtotell.com/Forum-PHP)
+---- Forum: How To Use Ajax In php Form Submitting (https://www.webtotell.com/Forum-How-To-Use-Ajax-In-php-Form-Submitting)
+---- Thread: How to post multiple forms with php and ajax (/Thread-How-to-post-multiple-forms-with-php-and-ajax)



How to post multiple forms with php and ajax - turgam - 03-03-2019

If you are dealing with multiple forms in a website, it's not the best way to write peace of code for individual javascripts to specific forms. This peace of code will help you to understand how you can arrange your html and using only one script to communicate with php from multiple forms while using ajax. 
Here is index.php
PHP Code:
<script type="text/javascript" src="jquery.js"></script>
<
form  name="contact1" action="contact.php" method="POST" id="contact1">    
<div>First Name: <input type="text" name="firstName" id="firstName"   required /></div> 
<div>Last Name <input type="text" name="lastName" id="lastName"  required /></div>
<
div><input type="submit" name="submit" value="Submit" /></div> 
</form>
<
form name="contact2" action="contact.php" method="POST" id="contact2">    
<div>First Name: <input type="text" name="firstName" id="firstName"   required /></div> 
<div>Last Name <input type="text" name="lastName" id="lastName"  required /></div>
<
div><input type="submit" name="submit" value="Submit" /></div> 
</form>
<
div id="results_contact1">contact1</div>
<
div id="results_contact2">contact2</div>

 
<script type="text/javascript">
$(
document).ready(function() {
$(
"form").submit(function() { 
// Getting the form ID
var formData= {} ;
var 
formID = $(this).attr('id');
// Getting form Details (text fileds)
var formDetails = $('#'+formID);
formData formDetails.serializeArray() ;
// inserting form ID to form detail's array or some called object 
formData.push({ name"formID"valueformID });

$.
ajax({
type"POST",
url'contact.php',
data:  formData,
success: function (data) { 
// Inserting html into the result div
$('#results_'+formID).html(data);

},
error: function(jqXHRtexterror){
            // is there any error  ? 
            $('#result').html(error);           
        
}
    });
return 
false;
});
});
</
script

and we need contact.php 
PHP Code:
<?php

if (isset($_POST['formID'])) {
switch (
$_POST['formID']){
case 
'contact1' : echo "contact1 form has been selected <br>" ; 
  
echo "First Name:" $_POST['firstName'] . " and Last Name:" $_POST['lastName'] ;
  break ; 
case 'contact2' : echo "contact2 form has been selected" ; 
  
break ;  
}
}

?>


also you need jquery.js to run this code, you can download from attachments.
[attachment=1]
I hope this helps for everyone