Monday, 11 June 2018

Auto Refresh Div Content using AngularJS in PHP


In this post we will learn How can we auto refresh any Div tag dynamic content or data by using AngularJS with PHP Script. Because refreshing content of any particular html element of web application page is one of the required functionality in Dynamic web development. For this JavaScript has provide us to use setInterval() method for execute the same task on regular interval with specified time. But we want to do this things in AngularJS, so AngularJS has the wrapper of setInterval() in $Interval angular service module. By using this angular service module we can repeat the same task on regular interval of time.

So, here for refresh a DIV or any element content or data in specified time, we have use $interval service. This Angular service has done same task which we have done by using setInterval() method of javascript but $interval has give us more control like promis callback which can be cancel or stop execute of refresh of data.

For learn how can we use $interval service for Auto refresh of Div content without refresh of web page. So, here we have use PHP script and make simple Chat application by using AngularJS with PHP. In this chat application we have load chat data in Div tag by using AngularJS function which call PHP script for fetch data from Mysql data and display under Div tag. Now we want to auto refresh this Div chat data on every 5 seconds, for this here we have use $interval service of Angular. This service we can use same as setInterval(), in this service also we have put our fetchData() function and set time interval of 5 seconds, so on every 5 second $interval service has called fetchData() function which send request to PHP script for fetch data from Mysql chat table and then after it will display under Div without refresh of webpage. If want to make robust web application by using AngularJS with PHP then this source code will helpful. So, this way it will auto refresh div content by using AngularJS $interval service with PHP.









Source Code



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `chat`
--

CREATE TABLE `chat` (
  `chat_id` int(11) NOT NULL,
  `chat_content` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `chat`
--
ALTER TABLE `chat`
  ADD PRIMARY KEY (`chat_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `chat`
--
ALTER TABLE `chat`
  MODIFY `chat_id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;


database_connection.php



<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");



?>


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Auto Refresh Div Content using AngularJS in PHP</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  #load_tweets
    {
      padding:16px;
      background-color:#f1f1f1;
      margin-bottom:30px;
    }
    #load_tweets li
    {
      padding:12px;
      border-bottom:1px dotted #ccc;
      list-style: none;
    }
  </style>
 </head>
 <body>
  <br />
   <h3 align="center">Auto Refresh Div Content using AngularJS in PHP</h3>
  <br />
  <div ng-app="autoRefreshApp" ng-controller="autoRefreshController" class="container" style="width:100%; max-width:600px;">
   <h3 align="center">Chat Page</h3>

   <div class="alert alert-success alert-dismissible" ng-show="success">
    <a href="#" class="close" aria-label="close">&times;</a>
    {{ successMessage }}
   </div>

   <form method="post" ng-model="form_data" ng-submit="submitForm()">
    <div class="form-group">
     <label>Enter Your Message</label>
     <textarea name="content" class="form-control" ng-model="form_data.content"></textarea>
    </div>
    <div class="form-group" align="right">
     <input type="submit" name="submit" class="btn btn-info" value="Send" />
    </div>
   </form>
   <div id="load_tweets">
    <ul>
     <li ng-repeat="messageData in messagesData">
      {{ messageData.chat_content }}
     </li>
    </ul>
   </div>
  </div>
 </body>
</html>

<script>

var app = angular.module('autoRefreshApp', []);

app.controller('autoRefreshController', function($scope, $http, $interval){

 $scope.success = false;

 $scope.submitForm = function(){
  $http({
   method:"POST",
   url:'insert.php', 
   data:$scope.form_data
  }).success(function(data){
   if(data.message != '')
   {
    $scope.form_data = null;
    $scope.success = true;
    $scope.successMessage = data.message;
    $interval(function(){
     $scope.success = false;
    }, 5000);
   }
  });
 };

 $scope.fetchData = function(){
  $http.get('fetch_data.php').success(function(data){
   $scope.messagesData = data;
  });
 };

 $interval(function(){
  $scope.fetchData();
 }, 5000);

});



</script>


insert.php



<?php

//insert.php

include("database_connection.php");

$form_data = json_decode(file_get_contents("php://input"));

if(!empty($form_data->content))
{
 $data = array(
  ':chat_content'  => $form_data->content
 );
 $query = "
 INSERT INTO chat 
 (chat_content) VALUES (:chat_content)
 ";
 $statement = $connect->prepare($query);
 if($statement->execute($data))
 {
  $output = array(
   'message' => 'Message Sended'
  );
  echo json_encode($output);
 }
}

?>


fetch_data.php



<?php

//fetch_data.php

include("database_connection.php");

$query = "SELECT * FROM chat ORDER BY chat_id DESC";

$statement = $connect->prepare($query);

if($statement->execute())
{
 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }
 echo json_encode($data);
}

?>

0 comments:

Post a Comment