In this tutorial we will see the easy example to post data using jQuery ajax and display them in the same page.
Lets start from the simple css :
#res{
border:solid 1px #000000;
margin:5px;
padding:5px;
width:300px;
visibility:hidden;
}
.error{
color:#FF0000;
}
The First res div used to show the result div when result return. And the second one is used to show error if the user did not enter name.
OK here we write the simple jQuery function, before function include jQuery file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"> </script>
Now the Function for the data post
<script type="text/javascript">
$(document).ready(function(){
$("#testme").click(function () {
$("#res").css('visibility','visible') ;
$("#res").html('Please wait requesting data...');
$.ajax({
type: "POST",
data: "name=" + $("#name").val(),
url: "taste.php",
success: function(msg){
$("#res").html(msg)
}
});
});
});
</script>
Now create input field with the id name and button to submit id testme because we already have defined them in function that name will be the elementid name and button will be elementid testme.
Enter Your Name : <input id="name" type="text" value="" /> <input type="button" id="testme" value="Send Message"/>
And in the last Create div with the id res because we are getting html return value in res div.
<div id="res"> </div>
The taste.php File:
<?php
if (isset($_POST['name'])) {
$name=$_POST['name'];
if($name!=""){
?>
<p>
<?php echo "Welcome ". $name;?>
</p>
<?php
}else{
?>
<p> Please Enter Your Name</p>
<?php
}
}
?>
Now the Full html code for mainpage:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#res{
border:solid 1px #000000;
margin:5px;
padding:5px;
width:300px;
visibility:hidden;
}
.error{
color:#FF0000;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#testme").click(function () {
$("#res").css('visibility','visible') ;
$("#res").html('Please wait requesting data...');
$.ajax({
type: "POST",
data: "name=" + $("#name").val(),
url: "taste.php",
success: function(msg){
$("#res").html(msg)
}
});
});
});
</script>
</head>
<body>
Enter Your Name : <input id="name" type="text" value="" /><input type="button" id="testme" value="Send Message"/>
<div id="res">
</div>
</body>
</html>














