Thursday, July 5, 2018

Ajax connection with PHP

When we start programming PHP, there comes a time when people start asking as to do the front-side of the application as well.
So we learn HTML, CSS and some JavaScript (and jQuery). We create great looking webpages with some animations.
But it's not enough: wouldn't it be better if the user would talk back with the server? And so we start delving into AJAX.
Here's a simple example on how it works.

Consider the follow index.php:


<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="ajaxRequest.js"></script>
</head>
<body>
    <select id="animalSelector">
        <?php
            require_once dirname(__FILE__) . '/DAL.php';
            $listAnimals = GetAnimals();
            foreach($listAnimals as $animal){
                $id = $animal['id'];
                $name = $animal['name'];
                echo "<option value=$id>$name</option>";
            }
        ?>
    </select>
    <select id = breedSelector>
        <?php
            require_once dirname(__FILE__) . '/DAL.php';
            $listBreeds = GetBreeds(1);
            foreach($listBreeds as $breed){
                echo "<option>$breed</option>";
            }
        ?>
    </select>
</body>
</html>


On the header it calls for jQuery and an yet to be created Javascript file.
On the body it creates two <select> elements which will be populated via php (theoretically from a database). Both <select> have an id so they can be accessed with our js file.

Our ajaxRequest.js file will wake up whenever the first <select> is changed and will run an ajaxReceiver.php file, in order to update the 2nd <select>.

$(document).ready(function(){
    $('#animalSelector').change(function(){
        var animalId = $('#animalSelector').val();
       
        $.ajax({
            url: 'ajaxReceiver.php',
            type: 'post',
            data: {
                action: 'getBreeds',
                id: animalId,
                XDEBUG_SESSION_START: 'netbeans-xdebug' //allows the code to be debugged with netbeans
            },
            success: function(output){
                $('#breedSelector').html(output);
            },
            error: function(error){
                alert("Error: " + error);
            }
        });
    });
});


Inside the Ajax brackets we define the parameters: url for which file to call, data are the parameters to send, and what to do after receiving a good or bad response.

The ajaxReceiver.php file's responsibility is to receive the ajax request, sanitize parameters, call the necessary functions to get data and to echo it back to the browser.

<?php
$action = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_SPECIAL_CHARS);
$animalId = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);

if($action == 'getBreeds'){
    require_once dirname(__FILE__) . '/DAL.php';
    $breedList = GetBreeds((int)$animalId);
    $response = "";
    foreach($breedList as $breed){
        $response .= "<option>$breed</option>";
    }
    echo $response;
}
?>


The DAL.php file, standing for Data Access Layer, should connect to a DB to retrieve data. For the simplicity sake, I've just hard coded the data directly.

<?php
    function GetAnimals(){
        $animal1 = array("id"=>1, "name"=> "dog");
        $animal2 = array("id"=>2, "name"=> "cat");
        $animal3 = array("id"=>3, "name"=> "horse");
       
        return array($animal1, $animal2, $animal3);
    }
   
    function GetBreeds($id){
        if($id===1){
            $a = array("German Shepherd", "Golden Retriever", "Dobermann");
            return $a;
        } else if($id===2){
            $a = array("Persian", "Siamese", "Maine Coon");
            return $a;
        } else if($id===3){
            $a = array("Mustang", "Arabian Horse", "Percheron");
            return $a;
        }
    }
?>


There are a ton of add-ons that this process could have, from a loading icon while the request is being processed to validation being handled on the client side.

I'll probably transfer this blog to another server which gives colour to my code.