PHP and AJAX

PHP and AJAX


AJAX refers to updating the webpage component without the entire page being reloaded.


What is AJAX

AJAX = Asynchronous JavaScript and XML.

AJAX is a rapid and dynamic webpage creation tool.

AJAX permits the asynchronous actualization of web pages through modest quantities of data to be exchanged with the server behind the scenes. This means that elements of a web page can be upgraded without the complete page reloading.

If the content should change, classic web pages (which do not use AJAX) need to reload the complete page.

Google Maps, Gmail, Youtube, and Facebook tabs are examples of AJAX apps.

You can also search for these topics, ajax in php, working of ajax in php, what is the use of ajax, ajax internet standards, php ajax example, google suggest to use php, Explain php ajax, what is php ajax.

How AJAX Works


PHP AJAX WORKS



You can also search for these topics, working of php ajax, how php ajax works, how php ajax works diagram.

AJAX is Based on Internet Standards

AJAX employs a mixture of The Internet standards :

  • XMLHttpRequest object (to exchange data asynchronously with a server)
  • JavaScript/DOM (to display/interact with the information)
  • CSS (to style the data)
  • XML (often used as the format for transferring data)

Browser and platform independence are key features of AJAX apps.



You can also search for these topics, internet standards in php ajax, php ajax internet standards, ajax based on internet standards using php.

Steps To Create An AJAX Program

There are few steps available to create an ajax program which is:

  1. Create an object for XMLHttpRequest class.
  2. Implement onreadystatechange event to check the status of request.
  3. Open a request connection with specified server page.
  4. Send request to server.

Create XMLHttpRequest Object

It is used to exchange data asynchronously from a server page.

The following syntax is used to create object is:

var xmlhttp = new XMLHttpRequest();

Implement onreadystatechange Event

It is used to track the status of our request with a server page. We can show different types of output depends on the request status.

The following syntax is used to implement onreadystatechange event is :

xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
    // Write your output code if request successful
}

Open Connection

It is used to exchange data asynchronously from a server page.

The following syntax is used to create object is:

xmlhttp.open("GET", "serverpage", true);

Send Request

After opening a connection, you can send the request to server.

The following syntax is used to send request is :

xmlhttp.send();

PHP and AJAX Example - Getting Server Date and Time

First we will create a html file called "showtime.html" and it contains a button to get and display the server date and time.

Example:- showtime.html

<!DOCTYPE html>
<html>
<head>
<script>
    function showServerTime() {         
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function (){
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("time").innerHTML = this.responseText;
            }
        }
        xmlhttp.open("GET", "showtime.php", true);
        xmlhttp.send();
    }
</script>
</head>
<body>
<button value="Show Server Time" onclick="showServerTime()">Show Server Time</button><br /><br />
<p>The server time is : <span id="time"></span></p>
</body>
</html>

Second we will create a php file called "showtime.php" and it contains the code to display the server date and time.

Example:- showtime.php

<?php
echo date("Y/m/d") . " " . date("H:i");
?>

Output:-



The server time is :



PHP and AJAX Example - Getting Hint Text Like Google Search Suggestions

This example shows how a Web page can communicate with a web server when a user type in a field.

First we will create a html file called "showhint.html" and it contains a button to get and display the server date and time.

Example:- showhint.html

<!DOCTYPE html>
<html>
<head>
<script>
    function showHint($str) {
        if (str.length == 0) {
            document.getElementById("hint1").innerHTML = "";
            return;
        } else {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("hint1").innerHTML = this.responseText;
                }
            }
            xmlhttp.open("GET", "gethint.php?q=" + str, true);
            xmlhttp.send();
        }
    }
</script>
</head>
<body>
<p><b>Start typing a country name in the input field below:</b></p>
<form action="">
  <label for="name">Country name:</label>
  <input type="text" id="name" name="name" onkeyup="showHint(this.value)">
</form>
<p>The suggestions are</p>
<p id="hint1"></p>
</body>
</html>

Second we will create a php file called "gethint.php" and it contains the code to display the hint text.

Example:- gethint.php

<?php
// Array with names
$a[] = "America";
$a[] = "Africa";
$a[] = "Australia";
$a[] = "India";
$a[] = "Iceland";
$a[] = "Brasil";
$a[] = "Britan";
$a[] = "Belgium";
$a[] = "Italy";
$a[] = "China";
$a[] = "Congo";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
  $q = strtolower($q);
  $len=strlen($q);
  foreach($a as $name) {
    if (stristr($q, substr($name, 0, $len))) {
      if ($hint === "") {
        $hint = $name;
      } else {
        $hint .= ", $name";
      }
    }
  }
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>

Output:-

Start typing a country name in the input field below:

The suggestions are


In the above example, a function called "showHint()" is used if a user types a character in the input field.

The function is called when the onkeyup event occurs.

Code explanation :-

To begin, make sure the input field is empty (str.length == 0). If that's the case, clear the hint1 placeholder's content and leave the function.

However, if the input field is not empty, do the following :

  • Generate an XMLHttpRequest object.
  • Generate a function that will be called once the server response is complete.
  • Send the application on the server to the PHP file (gethint.php).
  • The q argument has been added to the url (gethint.php?q="+str) as you can see.
  • The content of the input field is stored in the str variable.