I had a project where I needed to submit a form from an HTML page. The form data would be sent by ajax to a php file which would handle the data. The data could be insterted into a database. A result from the php file is then sent back to the HTML form and inserted into the results div id. The trick with this is to also remove text that was typed into the from in the first place.
<form id="ajaxform" name="ajaxform" action="assets/ajax/enquiry.php" method="post"> <div class="form-group name"> <label class="sr-only" for="name">Name</label> <input name="name" id="name" type="text" class="form-control" placeholder="Name:"> </div><!--//form-group--> <div class="form-group email"> <label class="sr-only" for="email">Email</label> <input name="email" id="email" type="email" class="form-control" placeholder="Email:"> </div><!--//form-group--> <div class="form-group message"> <label class="sr-only" for="message">Message</label> <textarea name="message" id="message" class="form-control" rows="6" placeholder="Message:"></textarea> </div><!--//form-group--> <button class="btn btn-lg btn-theme ">Send Message</button> </form><!--//form-->
This is where the results from the form that was submitted will be sent back to after being processed by the php script.
<!-- Results will be sent back to this div -->
<div id="result"></div>
This is the javascript / ajax call which is placed at the bottom of the HTML page.
<script type="text/javascript">
$("#ajaxform").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
type: "POST",
url: formURL,
data: postData,
dataType: "json",
success: function(dataType){
// Successful result will be sent to the result div id.
$("#result").html(dataType);
},
complete:function(){
//Clear the form
$('#ajaxform')[0].reset();
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
</script>
The form data is sent to this php script as directed in the form action. The php script receives the form information and then anything is possible. This short piece of code just verifies that the information has been received and sends back the return message to the orginal form.
if(!empty($_POST['name'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//Could insert this into the database.
$returnMessage = "The form has been submitted: $name ";
echo json_encode($returnMessage);
}if(!empty($_POST['name'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//Could insert this into the database.
$returnMessage = "The form has been submitted: $name ";
echo json_encode($returnMessage);
}
No comments:
Post a Comment