Hello friends hope you all are doing good and please be safe at your home in this pandemic situation.
Usually we use to save our html forms using our server side language but these days no body want to refresh the page after clicking the submit button. As it took much time to reload the page again and also it consumes more bandwidth of the server. To overcame from this situation now we use Ajax or Jquery to submit the form. In this tutorial i will show you how you can save html form using Ajax and php without page refresh. If you want to save form using php then read it here.
First of all we will divide it into 3 parts 1 is HTML form and 2nd is Ajax for getting the values and final is PHP part to get the values and save it to the database. Now we will start our working from 1st part which is creating HTML form.
I am not including any kind of stylesheet so please add it at your end or copy the bootstrap design and Scripts from below. You can use any version as i m giving you the outlook only.
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
HTML Form (Use bootstrap for this)
<div class="col-md-3"> <h2>Sign Up</h2> <form id="myform"> <label>First Name</label> <input type="text" name="firstname" class="form-control"> <label>Last Name</label> <input type="text" name="lastname" class="form-control"> <label>Email Address</label> <input type="text" name="email" class="form-control"> <br/> <input type="button" id="testit" value="Sign up" class="btn btn-primary "> <div class="clearfix"></div> </form> </div>
In the above code we have created the HTML form for filling out the data. Now we will written down the Ajax part to transfer this data to our PHP page.
Ajax Script
<script> $('#testit').click(function(){ var formdetails=$('#myform').serialize(); var url="postvalues.php"; $.ajax({ url:url, data:formdetails, method:"POST", success:function(result){ alert(result); }, error:function(error){ alert(error); } }) }) </script>
In the above code you can see that we are transferring our data to our PHP page you can see the url variable. In the “data” variable we are getting our whole form values. We have used the post method so we will transfer the data using POST to our PHP so while getting the data we have to use $_POST in our PHP.
PHP Script (postvalues.php)
echo "My Name is - $_POST[firstname] $_POST[lastname] and mail id is $_POST[email]";
Hope you like our tutorial if you have any advice then please comment below.
~ Stay Home Be Safe Use Mask ~