Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5

How to post multiple forms with php and ajax
#1

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.
.zip jquery.zip Size: 32.69 KB  Downloads: 0

I hope this helps for everyone
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)