Create a HTML form with id=”myform”, action=”userinfo.php”, and method=”post”. Add name and age text fields and add name attribute. Create a button, give it id=”sub”. Finally create a span with id=”result” and close it.
<form id="myform" action="userinfo.php" method="post">
Name:<input type="text" name="name"><br>
Age:<input type="text" name="age"><br>
<button id="sub">Save</button>
<span id="result"></span>
Create a new PHP file name it as userinfo.php. Write database connections and select the database. Now get the posted values in variables. Finally execute the MYSQL statement and echo the output.
<?php
//userinfo.php file
//Database connection
$conn = mysql_connect('localhost','root','');
$db = mysql_select_db('test');
//Posted values
$name = $_POST['name'];
$age = $_POST['age'];
if(mysql_query("Insert into user values('$name', '$age')"))
echo "Successfully inserted";
else
echo "Insertion failed";
?>
Now write the jQuery script, first we need to serialize the data taken from input boxes. Then post them using jQuery post method and append the result in span tags.
$("#sub").click(function(){
var data = $("#myform :input").serializeArray();
$.post( $("#myform").attr("action"), data, function(info){
$("#result").html(info);
clearinput();
});
});
In the above code clearinput() is the function we will talk about it later. Now when the form is submitted it should not redirect to PHP page. So we write the following code.
$("#myform").submit(function(){
return false;
});
Now every thing is fine. But the text fields are to be cleared when form is submitted. So we will write a code to clear the text fields. We will write clearinput() function to clear the fields.
function clearinput(){
$("#myform :input").each(function(){
$(this).val('');
});
}
Now let’s see the full code in one place.
<form id="myform" action="userinfo.php" method="post">
Name:<input type="text" name="name"><br>
Age:<input type="text" name="age"><br>
<button id="sub">Save</button>
<span id="result"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("#sub").click(function(){
var data = $("#myform :input").serializeArray();
$.post( $("#myform").attr("action"), data, function(info){
$("#result").html(info);
clearinput();
});
});
$("#myform").submit(function(){
return false;
});
function clearinput(){
$("#myform :input").each(function(){
$(this).val('');
});
}
</script>
0 comments:
Post a Comment