Blog postAjax with Angular and PHP

Ajax with AngularJS and PHP

Published May 14, 2016

Ajax is a technology that enables us to update parts of a webpage, without the need to reload the page. Ajax improves the user experience because it reduces the time it takes to update the content of a page, and the webpage is updated without a blink, so overall the webpage behaves more like a native application. A major example for AJAX can be found in Google Maps where we navigate from one map to another without reloading the page.

Ajax works by sending requests for data from the browser to the server, and the server that returns the requested data back to the browser. When a user performs actions like clicking a button or scrolling down the page, JavaScript code which listens to the event, sends a request to the server side, and the server process the request, and creates a response which is then sent back to the browser so it can be used to update the content of the page.

In AngularJS, we use the $http service that makes working with AJAX very simple. In this tutorial, we are going to develop a phone book application that can store people's names and phone numbers. The application enables us to add, read and delete the records. The server side is written in PHP.

The source code for the tutorial can be downloaded from the link in the conclusion section.

 

The Angular $http service

The $http service is what we use in Angular applications to perform Ajax calls. In order to use the service we first need to inject it as a dependency to the controller.

<script>
var ajaxExample = angular.module('ajaxExample', []);

ajaxExample.controller('mainController', function($scope, $http){

});   
</script>

The $http service has the following parts:

  • The method parameter defines if we get the data by GET or send the data by POST.
  • The url parameter defines the path to the server side (the PHP script).
  • Code to execute in case of success.
  • Code to run in case of failure.

For example,

$http({
   method: 'GET',
   url: 'api/get.php'
}).then(function (response) {
   // code to execute in case of success
}, function (response) {
   // code to execute in case of error
});

We need to fetch data from the server so we use the GET method, the PHP script is 'api/get.php'. The first callback (then) runs in case of success, and the second in case the server side fails to respond.

Now that we understand the basic syntax for doing AJAX in AngularJS apps, let's write the HTML for the app.

 

The HTML

index.html

The html part of the application has two parts.

  1. The first part is the form in which the user can fill new names and phone numbers.
  2. The second part contains a list of all the names and phone numbers.

Each of the list items can be deleted by pressing the 'delete' button.

We define the application by using ng-app on the html tag. The name of the application is 'ajaxExample'.

We define the controller on the div that wraps the form and the list with ng-controller = 'mainController'

The input fields are defined with ng-model:

  1. ng-model="newName" for the name
  2. ng-model="newPhone" for the phone number

We put ng-click="addPerson()" on the button, so clicking the button submits the new person data.

The list displays the names of all the records with ng-repeat.

Every list item contains a person's name and phone number and a button for deleting the person with the 'deletePerson' function.

<!doctype html>
<html ng-app="ajaxExample">
<head lang="en">
    <meta charset="utf-8">
    <title>Angular Ajax with PHP</title>
</head>
<body>

<h2>The form</h2>

<div ng-controller="mainController"

    <form> 
        <p>Fill the form</p>
        <div>
            <label>Name</label>
            <input type="text" ng-model="newName">
        </div>
            
        <div>
            <label>Phone</label>
            <input type="text" ng-model="newPhone">
        </div>
    
        <input type="button" value="Add" ng-click="addPerson()">
        
    </form>
    
    <h2>The list</h2>
    <p>The names that were added with the form.</p>
    
    <ul>
        <li ng-repeat="person in people">
            <button ng-click="deletePerson( person.id )">Delete</button> {{ person.name }} {{ person.phone }}
        </li>
    </ul>

</div>

<script src="/libs/angular-1.4.9.min.js"></script>
<script src="/assets/js/app.js"></script>

</body>
</html>

 

The Angular code

We write the AngularJS code in the file 'assets/js/app.js'.

The Angular code has 3 functions:

  1. getPeople() does an Ajax call to a PHP script that reads all the records from the database.
  2. addPerson() gets the data which was posted from the form and sends it with Ajax to a PHP script that inserts the new record to the database.
  3. deletePerson() gets the id of a record, and sends an Ajax call to a PHP script to delete the record from the database.
var ajaxExample = angular.module('ajaxExample', []);

ajaxExample.controller('mainController',function($scope,$http){
    $scope.people;

    $scope.getPeople = function() {
          $http({
              
              method: 'GET',
              url: '/api/get.php'
              
          }).then(function (response) {
              
              // on success
              $scope.people = response.data;
              
          }, function (response) {
              
              // on error
              console.log(response.data,response.status);
              
          });
    };

    $scope.addPerson = function() {
          $http({
              
               method: 'POST',
               url:  '/api/post.php',
               data: {newName: $scope.newName, newPhone: $scope.newPhone }
               
          }).then(function (response) {// on success
            
               $scope.getPeople();
            
          }, function (response) {
              
               console.log(response.data,response.status);
               
          });
    };

    $scope.deletePerson = function( id ) {

          $http({
              
              method: 'POST',
              url:  '/api/delete.php',
              data: { recordId : id }
              
          }).then(function (response) {
        
              $scope.getPeople();
        
          }, function (response) {
              
              console.log(response.data,response.status);
              
          });
        };

        $scope.getPeople();
});

 

The database

We store the data that we gather with the form in a people table.

That's the SQL code for the table:

CREATE TABLE IF NOT EXISTS `people` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

 

The PHP

The PHP server side will be in the 'api/' folder, and it has the following 4 scripts:

  1. api/connect.php to connect with the database.
  2. api/get.php that reads the data from the database.
  3. api/post.php that is used to add a record to the database.
  4. api/delete.php is used to delete a record from the database.

 

connect.php

<?php
// db credentials
define('DB_HOST', 'localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','angular');

// Connect with the database.
function connect()
{
  $connect = mysqli_connect(DB_HOST ,DB_USER ,DB_PASS ,DB_NAME);

  if (mysqli_connect_errno($connect))
  {
    die("Failed to connect:" . mysqli_connect_error());
  }

  mysqli_set_charset($connect, "utf8");


  return $connect;
}

 

get.php to read from the database

<?php
require 'connect.php';

$connect = connect();

// Get the data
$people = array();
$sql = "SELECT id, name, phone FROM people";

if($result = mysqli_query($connect,$sql))
{
  $count = mysqli_num_rows($result);

  $cr = 0;
  while($row = mysqli_fetch_assoc($result))
  {
      $people[$cr]['id']    = $row['id'];
      $people[$cr]['name']  = $row['name'];
      $people[$cr]['phone'] = $row['phone'];

      $cr++;
  }
}

$json = json_encode($people);
echo $json;
exit;

 

post.php to insert new records to the database

We get the data that is posted from the form with the following code:

file_get_contents("php://input")

The data needs to be json decoded. As you can see in the following code:

<?php
require 'connect.php';

$connect = connect();

// Add the new data to the database.
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
    $request     = json_decode($postdata);
    
    $newName  = preg_replace('/[^a-zA-Z ]/','',$request->newName);
    $newPhone = preg_replace('/[^0-9 ]/','',$request->newPhone);
    
    if($newName  == '' || $newPhone == '') return;

    $sql = "INSERT INTO `people`(`name`, `phone`) VALUES ('$newName','$newPhone')";

    mysqli_query($connect,$sql);
}
exit;

 

delete.php

Deletes a record from the database.

<?php
require 'connect.php';

$connect = connect();

// Delete record by id.
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
    $request = json_decode($postdata);

    $id  = (int)$request->recordId;

    $sql = "DELETE FROM `people` WHERE `id` = '$id' LIMIT 1";

    mysqli_query($connect,$sql);
}

 

Conclusion

This concludes our experimenting with AngularJS and PHP. Hope it helps. If you have any comments you may leave them in the comments box below.

Download the source code for the tutorial

comments powered by Disqus