AJAX - Programming With PHP


AJAX - Programming With PHP


Fig1. XAMPP Control Panel

  • Access the software “XAMPP Control Panel” from your installed program list and start Apache server as shown in the picture above.

AJAX PHP example code :

  • WikiTechy-PHP-Sample.php file to access query string variable
<?php 
  if ($_GET["data"] == "1") 
  { 
    echo 'The server got a value of 1'; 
  } 
  if ($_GET["data"] == "2")
  { 
    echo 'The server got a value of 2';
  }
?>


    Go to the drive where xampp is installed. Usually it installs in C: drive. Under xampp folder go to htdocsajax folder. 

    Save the above sample php code in this path with the file name “WikiTechy-PHP-Sample.php”.

Code Explanation :


    This line of code checks whether the query string variable “data” has the value “1” by the conditional code if ($_GET[“data”] == “1”).

    If the conditional code satisfies, the compiler is instructed to print the string in output console as “The server got a value of 1”.

    This line of code checks whether the query string variable “data” has the value “2” by the conditional code if ($_GET[“data”] == “2”).

    If the conditional code satisfies, the compiler is instructed to print the string in output console as “The server got a value of 2”.

Output :


    The php code is executed in the browser by passing the value “1” for the variable “data”.

    The php code is executed in the browser by passing the value “2” for the variable “data”.

AJAX example - Sample Code :

<html>  
<head>
    <title>Sending Data to the Server</title>
    <script language = "javascript"> 
        function getData(str)
        {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() 
            {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
                {
                    document.getElementById("targetDiv").innerHTML = 
			xmlhttp.responseText;
                }
            };
            xmlhttp.open("GET", "WikiTechy-PHP-Sample.php?data=" + str, true);  xmlhttp.send();
        } 
    </script>
</head>  
<body>
    <h1>Sending Data to the Server</h1>
    <form> 
        <input type = "button" value = "Fetch message 1"  
        onclick = "getData(1)"> 
        <input type = "button" value = "Fetch message 2"  
        onclick = "getData(2)">
    </form>
    <div id="targetDiv">
        <p>The fetched message will appear here.</p>
    </div>  
</body>  
</html>

Code Explanation :

    The line “<script language = "javascript">” indicates / informs the compiler that the language for script code is “javascript”.

    Start the function code function getData(str) to start listening to XMLHTTPRequest();

    Declare a variable for the XMLHTTPRequest(); class.

    When any request is sent to a server, some decisions are made and implemented based on the response. The onreadystatechange event is fired each time when the readyState changes.

    The readyState property contains the status of the XMLHttpRequest. It is a value between 0 to 4 that has the following meaning :

0 : request not started 

1 : server connection is successful

2 : request received by the server

3 : server is processing the request 

4 : request completed and response is ready

  • The status property informs whether requested data is found or not. It has the below values :

200 : Found

404 : Not found


    Each and every request to server will be given a response value. This value indicated by the responseText is assigned to the innerHtml attribute of the div tag named “targetDiv”.

    XMLHttpRequest formulates HTTP send requests is a simple manner. Here the object of the class XMLHttpRequest, opens an URLto send a request. The open () method has three parameters :

  • First Parameter Value: GET or POST
    • This is the type of request sent to server.
    • GET is simpler request but has size limitations and security issues.
    • POST is faster, can accept larger quantity of data and secure in a way than GET.
  • Second Parameter Value: The location of the server file. 
    • The server file URL needs to be called with a query string parameter along with its value. 
    • This value is taken from the variable “str”, which is a parameter for the function getData().
  • Third parameter value:
    • true – indicates that it is an asynchronous call to the server. If the value is false then it indicates a synchronous call. By default, the value is “true”.

    send() – sends request to the server URL.

  • <form> - HTML <form> element signifies an interactive part of HTML content that can be used to send request to a server. 

    Using this <form> element, two button elements are placed in it. 

     The first button, place a server request. by passing the value 1” to the javascript method parameter “str”. 

    The second button, place a server request by passing the value 2” to the javascript method parameter “str”.

    <div> element, with an identifier name “id”, is placed here to receive and display server response.


Output :