Ajax Examples - XMLHttpRequest - PHP Array To Material List

| Page Views: 279 ajax

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. T

he 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


  • 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


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.

    class ArrayServer
        public function sendSpacecrafts()
            echo json_encode($spacecrafts);


    $arrayserver=new ArrayServer();


  • 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.

    var HttpClient = function () {

        var requestType = "GET";
        var isAsynchronous = true;

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

            var xmlhttprequest = new XMLHttpRequest();
            xmlhttprequest.onreadystatechange = function () {

                if (this.readyState == 4){

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

            xmlhttprequest.open(requestType, targetURL, isAsynchronous);


    function getArray(targetURL) {
        var client = new HttpClient();
        client.get(targetURL, function (receivedData) {
            var spacecrafts = JSON.parse(receivedData);



    function createListVew(spacecrafts)

        var listView=document.createElement('ol');

        for(var i=0;i<spacecrafts.length;i++)
            var listViewItem=document.createElement('li');

        return listView;



  • 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">
        <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"/>
    <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>

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

    <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>

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

    <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 class="col l3 s12">
                    <h5 class="white-text">Settings</h5>
                        <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>
                <div class="col l3 s12">
                    <h5 class="white-text">Connect</h5>
                        <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>

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



  • Video version of this tutorial.



  • Download the Project below:


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.


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


How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.


What do You Think

Previous Post Next Post