Monday, 7 January 2013

Jquery with Ajax Demo


Hi Friends,
Today In this post am explaining a simple Jquery demo.

In this example I have two Buttons which represents two colors and one input text field.
If we type any text in that filed and then press any of two buttons, the text we entered should be displayed in the clicked color and this response should come from a PHP page through ajax.

here is the sample output:


if we click on blue button the out put will be


if we click on red button the output will be



All these process should happen through ajax. For this we need one HTML file with Jquery or javaascript(Here an using jquery)  and one php file to give response. Here is the code:


index.html


<html>
<head>
        <!--including jquery file to make jquery work in this html file -->
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
  $(document).ready(function(){
$(".check").click(function(){
         //posting parameters to php page through ajax post method
       $.post("ajax.php", 

name : $("#uname").val(),    //entered text
color : $(this).val();                //clicked button value
} ,
function(data) {
                //here data is the response I'll get from php page
$("#result").html(data);
});
});
  });
</script>
</head>
<body>
<span id="result"></span><br>
Name: <input type="text" name="uname" id="uname">
<input type="button" name="check" class="check" value="blue">
<input type="button" name="check" class="check" value="red">
</body>
</html>


ajax.php


<?php
           echo "<span style='color:".$_REQUEST['color']."'>hello ".$_REQUEST['name']."</span>";
?>



No comments:

Post a Comment