Header menu

_________________________________________________________________________________

Monday, 16 September 2013

Send and receive data in ajax/jquery

How to send and receive data in ajax/jquery 

Sample Ajax tutorial in php



We will need two file for this tutorial ...
1. which send request and receive responce (test.php)
2. which receive request and send response (page.php)

On click of button ..the id of button will be send to page.php

And the response which we will get will replace html content of span id "val" .

test.php

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
    $( ".button" ).on("click",function(){

        $.ajax({
        type:"post",
url: "page.php",
data: {id:$(this).attr('id')},
success: function( data ) {
$( "#val" ).html( "<strong>" + data + "</strong> " );
}
});
        });
});
</script>
</head>
<body>
<button type="button" id="b1" class="button">Button-1</button>
<button type="button" id="b2" class="button">Button-2</button>
<button type="button" id="b3" class="button">Button-3</button>
</br></br></br>
<span id="val" style="background-color:#454282;">Which button is clicked ?<span>

</body>

</html>

---------------------------------------------------------------------------------------------------------------------------
page.php

<?php
$id=$_POST['id'];
if($id=="b1"){
echo "Button 1 is clicked ";
}
if($id=="b2"){
echo "Button 2 is clicked ";
}
if($id=="b3"){
echo "Button 3 is clicked ";
}

?>