Passing Data to the Server with GET using AJAX

When using the GET method of fetching data from the server, data is sent from Web pages back to the server using URL encoding, which means data is appended to the URL that is read back from the server.

choose_msg.php

<?php
if($_REQUEST{"data"}=="1")          // If a value '1' is sent to the server
{
  echo "You sent the server a value of 1";
}
if($_REQUEST{"data"}=="2")        // If a value '2' is sent to the server
{
  echo "You sent the server a value of 2";
}
?>

AJAX Code :

<html>
<head>
<title>An AJAX DEMO</title>
<script language="javaScript">
var XMLHttpRequestObject=false;
if(window.XMLHttpRequest)
{
   XMLHttpRequestObject=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
   XMLHttpRequestObject=new ActiveXObject("Micosoft.XMLHTTP");
}
function getData(dataSource,divID)
{
   if(XMLHttpRequestObject)
     {
        var obj=document.getElementById(divID);
        XMLHttpRequestObject.open("GET",dataSource);
            XMLHttpRequestObject.onreadystatechange=function()
            {
               if(XMLHttpRequestObject.readyState==4 && XMLHttpRequestObject.status==200)
                 {
                    obj.innerHTML=XMLHttpRequestObject.responseText;
         }
            }
        XMLHttpRequestObject.send(null);
  }
}
</script>
</head>
<body>
<h3>Sending AJAX data with GET</h3>
<form>
<input type="button" value="Retrieve Message 1" onclick="getData('choose_msg.php?data=1','targetDiv')">
<input type="button" value="Retrieve Message 2" onclick="getData('choose_msg.php?data=2','targetDiv')">
</form>
<div id="targetDiv">
<p>The retrieved message will appear here</p>
</div>
</body>
</html>

Before executing the program :

 Clicking on "Retrieve Message 1"


Clicking on "Retrieve Message 2"


The 1st button sends value '1' to the server and according the php file prints "You sent the server a value of 1".
Similarly, the 2nd button sends value '2' to the server and accordingly the php file prints the conditional output.

Top