Home

Tuesday, September 13, 2011

Submit Form without Refreshing Page with Jquery

Contact.html
<div id="preview"> </div>
<div id="formbox">
<form id="form" action="submit.php" method="post">
Name
<input type="text" name="name" />
Email
<input type="text" name="email" />
Message
<textarea name="message"></textarea>
<input type="submit" value="Submit">
</form>
</div>
Contacts
Table contains name, email, message and created data etc.
CREATE TABLE `contact` (
`id` int(11) AUTO_INCREMENT PRIMARY KEY,
`name` varchar(255) UNIQUE KEY,
`email` varchar(100),
`message` text UNIQUE KEY,
`created_date` int(11),
)
submit.php
Contails simple PHP code. Inserting values into contacts table.
<?php
include("db.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$name=mysql_real_escape_string($_POST['name']);
$email=mysql_real_escape_string($_POST['email']);
$message=mysql_real_escape_string($_POST['message']);
if(strlen($name)>0 && strlen($email)>0 && strlen($message)>0)
{
$time=time();
mysql_query("INSERT INTO contact (name,email,message,created_date) VALUES('$name','$email','$message','$time')");
echo "<h2>Thank You !</h2>";
}
}
?>
Validate Plugin
Here the collaboration of jQuery validate and form plug-in.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>
<script type="text/javascript">
$('document').ready(function()
{
$('#form').validate(
{
rules:
{
"name":{
required:true,
maxlength:40
},
"email":{
required:true,
email:true,
maxlength:100
},
"message":{
required:true
}},

messages:
{
"name":{
required:"This field is required"
},
"email":{
required:"This field is required",
email:"Please enter a valid email address"
},
"message":{
required:"This field is required"
}},

submitHandler: function(form){
$(form).ajaxSubmit({
target: '#preview',
success: function() {
$('#formbox').slideUp('fast');
}
});
}

})
});
</script>
db.php
PHP database configuration file
<?php
$mysql_hostname = "Host name";
$mysql_user = "UserName";
$mysql_password = "Password";
$mysql_database = "Database Name";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>

No comments:

Post a Comment

rathoddhirendra.blogspot.com-Google pagerank and Worth