Ajax Examples S1E1 : PHP - Serve Date and Time

Ajax has been around for over a decade. During this time it has revolutionized the web. We now take it fro granted how useful it has been and users are now used to respnsive ajax powered web applications. Ajax stands fro Asynchronous Javascript and XML. It comprises three technologies : Javascript, HTML and XML. Ajax allows updating of data in a web app without full page reloading. This saves data. Moreover, its asynchronous hence the user interface remains responsive. This is our first in a series that we will do over some time. It's introductory. We see how to get date from a server and show it in our webpage via javascript and html. Our server side language is php. We use the native XMLHttRequest object in this class.

Tools Used

Language : PHP 7, HTML, Javascript Platform : Backend and Fronted Web IDE : PHPStorm Server : Uniform Server/WAMP/Xampp Topics : Object Oriented PHP, Javascript Ajax, GET requests, Javascript XMLHttpRequest.

Questions this Project answers.

  • Ajax example with php.
  • Get datetime from php server and show via ajax javascript.
  • Javascript XMLHttpRequest example.
  • GET Request in javascript ajax with XMLHttpRequest.

Libraries Used

These are the third party CSS and JS used in this project.
  • None

Project Structure

  • Here's the structure of the project.
Ajax Get DateTime Project Structure

Screenshot

  • Here's the screenshot of the project. Ajax Get DateTime Fromserver

Source Code

Lets have a look at the source code. [su_tabs] [su_tab title="TimeServer.php"]
  • Our TimeServer class.
  • Servers the datetime from the server to the client.
<?php


class TimeServer
{

    /*
     * GET DATE AND TIME
     */
    public function sendDateTime()
    {
        $datetime=new DateTime('now',new DateTimeZone('Africa/Nairobi'));

        echo $datetime->format('Y-m-d H:i:s a');;
    }

}

//SEND DATE AND TIME
$timesever=new TimeServer();
$timesever->sendDateTime();
 

main.js

  • Our main.js javascript file.
  • Contains our custom HTTPClient class that makes request to the server via ajax.



/*
 0 	UNSENT 	Client has been created. open() not called yet.
 1 	OPENED 	open() has been called.
 2 	HEADERS_RECEIVED 	send() has been called, and headers and status are available.
 3 	LOADING 	Downloading; responseText holds partial data.
 4 	DONE 	The operation is complete.
 */


/*
HTTP CLIENT CLASS
 */
var HttpClient = function () {

    //INSTANCE VARIABLES
    var requestType = "GET";
    var isAsynchronous = true;

    //GET FUNCTION
    this.get = function (targetURL, onMyDataRetrieved) {

        //AJAX USING XMLHTTPREQUEST
        var xmlhttprequest = new XMLHttpRequest();
        xmlhttprequest.onreadystatechange = function () {

            //IF OPERATION IS COMPLETED
            if (this.readyState == 4){

                //IF HTTP RESPONSE STATUS IS OK:200
                if(this.status == 200) {
                    onMyDataRetrieved(this.responseText);
                }else
                {
                    onMyDataRetrieved("Error, the Request has not succeeded")
                }
            }
        };

        //OPEN CONNECTION AND SEND ASYNCHRONOUS REQUEST
        xmlhttprequest.open(requestType, targetURL, isAsynchronous);
        xmlhttprequest.send();
    }

}

/*
IMPLEMENT OUR HTTP CLIENT GET REQUEST
 */
function getDateTime(targetURL) {
    var client = new HttpClient();
    client.get(targetURL, function (receivedData) {
        document.getElementById("displaySectionID").innerHTML =receivedData;
    });

}
 

index.html

  • Our HTML file.
  • Defines our user interface.
  • Shows the datetime from the server.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax Time Server</title>
</head>

<body style="background-color: cornflowerblue; font-family: Roboto; ">
<h1>Ajax Beginner Example</h1>
<h3>Get Date From Server</h3>
<div style="font-style: italic" id="displaySectionID">
    <p>In this example we see how to load text from the server to our app via ajax</p>

</div>
<button onclick="getDateTime('TimeServer.php');">Load Date</button>

<script src="main.js"></script>
</body>
</html>
 

Video/Demo

  • Video version of this tutorial.
https://youtu.be/MDk2fYmcW8A

Download

  • Download the Project below:
Download  

How to Download and Run.

  1. Download the project above.
  2. You'll get a zipped file,extract it.
  3. Place it in the root directory of your server.
  4. Make sure server is running. Point the browser to that base url to see your site.
  5. That's it.

More

  • Visit our channel for more examples like these.
  • Lets share tips and ideas in our Facebook Page.
Oclemy,Cheers.