AngularJS Add,Edit,Update,Delete using Bootstrap modal with DataTable in PHP - Mostlikers

04 September, 2017

AngularJS Add,Edit,Update,Delete using Bootstrap modal with DataTable in PHP

Hi Guys, Today we are going to see How to use AngularJS Add, Edit, Update, Delete using Bootstrap modal with DataTable in PHP. AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application projects. By using this application without refresh the page you can get server-side response. In this tutorial, I have created a simple way to learn angular js curd operation. Follow the below simple setup process.


Live Demo           Download

Follow below steps :
  • Setup database connection
  • Load AngularJS and Bootstrap CDN
  • Load Html Template File
  • AngularJs Controller Setup
  • Server Side Scripting

Step 1:- Database Connection

Create a new table as users_information with below structure. insert some dumping data. This data will load bootstrap model.
CREATE TABLE `users_information` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `position` varchar(50) NOT NULL,
  `dob` date NOT NULL
)

DB Configuration

create a new file as config.php then paste the copied below code inside the file.
<?php
    $user = 'root';
    $password = '';
    $database = 'database';
    $db = new mysqli('localhost',$user,$password,$database);
    if(!$db):
        echo 'Your database connection not exist'; exit;
    endif;
?>

Step 2:- Load Bootstrap and Angular CSS and JS

Load Bootstrap CDN file to your <HEAD> tag. ng- app - The ng-app directive tells AngularJS that this is the root element of the AngularJS application.

<html ng-app="my_app">
<head>
    <title>AngularJS Add,Edit,Update,Delete using Boostrap modal </title>
    <link href='http://www.mostlikers.com/favicon.ico' rel='icon' type='image/x-icon'/>
    <!--Bootstrap CSS --> 
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/dataTables.bootstrap.min.css" rel="stylesheet">
    <link href="css/custom-style.css" rel="stylesheet">
    <!--/Bootstrap CSS --> 
    
    <!--JQuery DataTables--> 
    <script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/dataTables/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="js/dataTables/dataTables.bootstrap.min.js"></script>
    <!--/JQuery DataTables --> 
    
    <!--Angualrjs --> 
        <script type="text/javascript" src="js/angularjs/angular.min.js"></script>
        <script type="text/javascript" src="js/angularjs/angular-datatables.min.js"></script>
        <script type="text/javascript" src="js/angularjs/users_dump.angular.js"></script>
    <!--/Angualrjs --> 
</head>


Load HTML Template

Create a new index.html file load angular ajax call dynamic data responses.

  • data-ng-init - execute the angular controller function on page load. Here I am using a usersInformation() function to get all user information server side response. 
  • ng-repeat - make a loop for JSON object data. ex : users_list scope value (user in user_list) user scope object value. 
  • {{ }} or ng-bind - To bind the JSON object value. {{user.dynmaic value name}}


<div ng-controller="users" data-ng-init="usersInformation()" class="container">
    <div class="col-md-12">
        <div class="add_panel">
            <a ng-click="addModal();" class="model_form btn btn-primary">
                <i class="glyphicon glyphicon-plus"></i> Add User</a>
            <div class="clearfix"></div>
        </div>
        <div class="table-responsive">
            <table datatable="ng"  id="examples" 
                class="table table-striped table-bordered" cellspacing="0" 
                    width="100%">
                <thead>
                    <tr>
                        <th>S.No</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Position</th>
                        <th>Data Of Birth</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="user in users_list">
                        <td>{{$index + 1}}</td>
                        <td>{{user.name}}</td>
                        <td>{{user.email}}</td>
                        <td>{{user.position}}</td>
                        <td>{{user.dob | date: "yyyy-MM-dd"}}</td>
                        <td>
                            <a href="javascript:void(0);" ng-click="EditModal(user);"> 
                                <i class="glyphicon glyphicon-pencil"></i>
                            </a>
                            <a href="javascript:void(0);" ng-click="DeleteModal(user)"> 
                                <i class="glyphicon glyphicon-remove"></i> 
                            </a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div ng-if="success_msg" class="success_pop alert alert-success">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
             <strong> {{success_msg}} </strong> 
        </div>
    </div>
</div>   



Step 3:- Angularjs Controller

Create a new controller file user.angular.js load curd functions.
  • First, create app module name (my_app) to the angular control. 
  • Load the curd function usersInformation () - Get server side response using ajax call
  • $scope.addModal - Load boostrap modal function. Here i am calling new usersInformation add boostrap modal.
  • $scope.UserAddUpdate  - After submit form, $scope value post to the server side. (both add and edit in singal function)
  • $scope.EditModal - Loading 1 row value to boostrap modal, angular.copy() - Copy the ng repeat row value.
  • $scope.DeleteModal - Delete ng repeat object value by using this $scope.users_list.splice(index, 1); code.
var myapp = angular.module('my_app',['datatables']);
myapp.controller('users', function($scope,$http){
    $scope.master = {};
    $scope.usersInformation = function () {
        $http({ 
            method: 'GET',
            url: 'get_users.php'
        })
        .then(function (success){
            $scope.users_list = [];
            $scope.users_list =success.data;    
        },function (error){
                console.log(error);
        });
    };
$scope.addModal = function() {
        $scope.users_form = angular.copy($scope.master);
        $scope.form_name = 'Add New User Information';
        $('#form_modal').modal('show');
    };
$scope.UserAddUpdate = function (users_form) {
       var users_information = users_form;
       $http({
         method: 'POST',
         url: 'UserAddUpdate.php',
         data: users_information,
        }).then(function(response) {
            $scope.usersInformation();
            $scope.success_msg = response.data;
        },function (error){
            console.log(error);
        });
       $('#form_modal').modal('hide');
    };
$scope.EditModal = function(user) {
        $scope.form_name = 'Edit User Information';
        var edit_form = {};
        angular.copy(user, edit_form);
        $scope.users_form = edit_form;
        $scope.users_form.dob = new Date($scope.users_form.dob);        
        $('#form_modal').modal('show');
    };
$scope.DeleteModal = function(user) {
        var r = confirm("Are you sure want to delete ?");
        if (r == true) {
            var users_record_id = user.id;
            $http({
                method: 'POST',
                url: 'UserDelete.php',
                data: users_record_id,
            }).then(function(response) {
                var index = $scope.users_list.indexOf(user);
                $scope.users_list.splice(index, 1); 
                $scope.success_msg = response.data;
            },function (error){
                console.log(error);
            });
        }
    };
});

Step 4:- PHP Script Response 

     You can use any PHP framework,.Net framework, Webservices For Server side curd operation. Just give your response in JSON format the above angular script will work. I have some little bit knowledge in PHP Script. So I am using PHP Script for Add, edit, delete usersInformation. For a beginner, I would suggest PHP curd operation (PHP Curd operation with bootstrap modal) tutorial.

Get Users Information(get_users.php)

Fetch all the rows in the users_information table. Convert PHP response has JSON parse.

<?php
    include('config/config.php');
    $users_information = array();
    if ($result = $db->query("SELECT * FROM users_information")) {

        while($row = $result->fetch_array(MYSQL_ASSOC)) {
                $users_information[] = $row;
        }
        echo json_encode($users_information);
    }
    
?>

New user Add/Update (UserAddUpdate.php)

<?php
    include('config/config.php');
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        $ajax_data = json_decode(file_get_contents('php://input'), true);
        $name       = $db->real_escape_string($ajax_data['name']);
        $email      = $db->real_escape_string($ajax_data['email']);
        $position   = $db->real_escape_string($ajax_data['position']);
        $date       = new DateTime($db->real_escape_string($ajax_data['dob']));
        $user_dob   = $date->format('Y-m-d');
        $id         = (@$ajax_data['id']!="") ? 
        $db->real_escape_string(@$ajax_data['id']) : '';
        if($id!="") :
            $query = " UPDATE users_information SET name= '$name', email='$email',
             position='$position',dob='$user_dob' WHERE id=$id";
            $msg = "Successfully Updated Your Record";
        else: 
            $query = " INSERT INTO users_information SET name= '$name', email='$email',
             position='$position',dob='$user_dob'";
            $msg = "Successfully Inserted Your Record";         
        endif;
        $sql = $db->query($query);
        echo $msg;
    }   
?>

Delete user information (UserDelete.php)

<?php
    include('config/config.php');
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        $ajax_data = json_decode(file_get_contents('php://input'), true);
        $id = ($ajax_data!="") ? $db->real_escape_string($ajax_data) : '';
        if($id!="") :
            $query = "DELETE FROM users_information WHERE id=$id";
            $sql = $db->query($query);
            $msg = "Successfully Deleted Your Record";
        else:  
            $msg = "Something went wrong Please Check Reload your File.";
        endif;
        echo $msg;
    }   
?>

Bootstrap Modal

Bootstrap model form model copy and paste this code to index.php file. This model design won't visible until to call the jquery function.
<form  method="post" ng-submit="UserAddUpdate(users_form);" id="cat_form">
  <div class="modal-body with-padding">
    <div class="form-group">
      <div class="row">
        <div class="col-sm-12">
          <label>Name :</label>
           <input type="text" name="name" ng-model="users_form.name" 
                id="name" required="required" class="form-control">
        </div>
      </div>
    </div>            
    <div class="form-group">
      <div class="row">
        <div class="col-sm-12">
          <label>Email :</label>
           <input type="email" name="email" ng-model="users_form.email" 
                id="email" required="required"  class="form-control email">
        </div>
      </div>
    </div>
    <div class="form-group">
      <div class="row">
        <div class="col-sm-12">
          <label>Position :</label>
           <input type="text" name="position" ng-model="users_form.position" 
                id="position" required="required"  class="form-control">
        </div>
      </div>
    </div>
      <div class="row">
        <div class="col-sm-12">
          <label>Birthday :</label>
           <input type="date" placeholder="yyyy-MM-dd" id="dob" 
                    max="<?php echo date('Y-m-d'); ?>" ng-model="users_form.dob" 
            class="form-control" required="required"  name="dob">
        </div>
      </div>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
      <button type="submit" name="form_data" class="btn btn-primary">Submit</button>
    </div>
</form>

OUTPUT
Try Your self >>

5 comments: