Ajax Examples - XMLHttpRequest - PHP Array To Material List

September 2, 2017 Oclemy XMLHttpRequest 6 minutes, 4 seconds

Asynchronous Javascript and XML(Ajax) is a technique for loading data from the server via HTTP requests in the background without reloading the full webpage. This ensures fast and responsive desktop like apps. You don't have to reload the whole page just because you want to rate a post or subscribe to a channel. Imagine a situation where you are watching some funny cat video in youtube and you want ti subscribe. You are in a terrible hotel wifi and it's taken a while for the video to load. You hit that subscribe button and the whole page loads. Your uncached videos start reloading again just because you've subscribed. Why could it just subscribe me in without reloading the whole page. Well, that's where ajax comes in. In this class we see how to fetch a simple php array from the server to our javascript app via ajax. We use the native XMLHttpRequest class to make a HTTP GET request. The array will be served to us in json format. So we simply parse using JSON.parse() method. We then fill a material list with our data from the server.

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,Ajax List

Questions this Project answers.

  • Get array from php to javascript via ajax.
  • Ajax PHP example GET request.
  • Fill ListView from the server via ajax in javascript.
  • Materialize List Ajax.

Libraries Used

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

  • MaterializeCSS

Screenshot

  • Here's the screenshot of the project. Ajax Fill List From Server

Project Structure

  • Here's the structure of the project.

Ajax Get PHP Array To List Project Structure

Source Code

ArrayServer.php

Lets have a look at the source code. [su_tabs] [su_tab title="ArrayServer.php"]

  • Our ArraySever class.
  • Servers array of spacecrafts from the server to client.
  • First we json encode our data so its parseable by the client.
    <?php

    class ArrayServer
    {
        public function sendSpacecrafts()
        {
            $spacecrafts=["Casini","Spitzer","Enterprise","Hubble","Voyager","Galileo","Pioneer","WMAP"];
            echo json_encode($spacecrafts);
        }

    }

    $arrayserver=new ArrayServer();
    $arrayserver->sendSpacecrafts();

main.js


  • Our main.js javascript file.
  • Contains our custom HTTPClient class that makes request to the server via ajax.
  • Gets json data from server and parses it to asimple javascript array.
  • We then bind this data to a list.
    /*
     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 getArray(targetURL) {
        var client = new HttpClient();
        client.get(targetURL, function (receivedData) {
            var spacecrafts = JSON.parse(receivedData);
            document.getElementById("displaySectionID").appendChild(createListVew(spacecrafts));

        });

    }

    /*
    CREATE LIST TO SHOW OUR DATA
     */
    function createListVew(spacecrafts)
    {

        var listView=document.createElement('ol');
        listView.className="collection";

        for(var i=0;i<spacecrafts.length;i++)
        {
            var listViewItem=document.createElement('li');
            listViewItem.className="collection-item";
            listViewItem.appendChild(document.createTextNode(spacecrafts[i]));
            listView.appendChild(listViewItem);
        }

        return listView;
    }

 

index.html


  • Our HTML file.
  • Defines our user interface.
  • We use materialize css to style our page and list.
  • Fills the material list with data from the server.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Ajax PHP Array</title>
        <!-- CSS  -->
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link href="assets/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
        <link href="assets/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
    </head>
    <body>
    <nav class="light-blue lighten-1" role="navigation">
        <div class="nav-wrapper container"><a id="logo-container" href="#" class="brand-logo">Camposha.info</a>
            <ul class="right hide-on-med-and-down">
                <li><a href="#">Home</a></li>
            </ul>

            <a href="#" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a>
        </div>
    </nav>

    <div class="container">
    <h1 class="header center orange-text">Ajax Beginner Example</h1>
    <h4 class="center light-blue-text">Get Array From Server</h4>
    <div id="displaySectionID">
        <p>In this example we see how to load Array from the server to our app via ajax</p>

    </div>
    <button class="btn-large waves-effect waves-light green" onclick="getArray('ArrayServer.php');">Fetch Array</button>
    </div>
    <br>
    <br>
    <br>
    <br>

    <br>
    <footer class="page-footer orange">
        <div class="container">
            <div class="row">
                <div class="col l6 s12">
                    <h5 class="white-text">Company Bio</h5>
                    <p class="grey-text text-lighten-4">We are a team of college students working on this project like it's our full time job. Any amount would help support and continue development on this project and is greatly appreciated.</p>

                </div>
                <div class="col l3 s12">
                    <h5 class="white-text">Settings</h5>
                    <ul>
                        <li><a class="white-text" href="#!">Link 1</a></li>
                        <li><a class="white-text" href="#!">Link 2</a></li>
                        <li><a class="white-text" href="#!">Link 3</a></li>
                        <li><a class="white-text" href="#!">Link 4</a></li>
                    </ul>
                </div>
                <div class="col l3 s12">
                    <h5 class="white-text">Connect</h5>
                    <ul>
                        <li><a class="white-text" href="#!">Link 1</a></li>
                        <li><a class="white-text" href="#!">Link 2</a></li>
                        <li><a class="white-text" href="#!">Link 3</a></li>
                        <li><a class="white-text" href="#!">Link 4</a></li>
                    </ul>
                </div>
            </div>
        </div>

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

 

Video/Demo


  • Video version of this tutorial.

https://youtu.be/CF9eYeEiE8A

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.

Comments