Subscribe via RSS Feed

Angularjs with Server Side Interaction

June 17, 2014 4 Comments

Why we are in need of server side scripting with Angular.js?

Every SPA framework out there relies on some type of service (RESTful or otherwise) to serve and process data. That’s the obvious role that servers can play with SPAs. What’s not quite as obvious are the other roles that the server can play as a SPA interacts with it. Here are some detail articles related to client side works in angular.js.

Validation:

Talking about server side scripting , and the first thing comes to our mind is validation. As with client-side security, client-side validation is a frail solution that can’t stand on its own. All validation of SPA data has to be validated on the server to ensure that the client-side code, and data haven’t been tampered with.

Service & Caching:

The server typically exposes a RESTful service to SPA clients to make it easy to GET, PUT, POST, or DELETE data. This can be done using Node.js, ASP.NET Web API, PHP, cloud services like Firebase, and many other frameworks using HTTP, Web Sockets, or another technique. As mentioned earlier, this is the most obvious role played by the server when building SPAs.
Some applications consume data that doesn’t change very frequently on the server. This type of data can often be shared across users. Servers are great at caching data so that queries to the data store are minimized. Whether you’re using Node.js, ASP.NET MVC, PHP, or one of the many other server-side frameworks, you more than likely have access to caching functionality that can increase the scalability of your application significantly. It’s something that I always try to plan for as I think through the role of the server in SPAs and other types of applications.

View Caching:

In addition to data caching, the server may also be used to cache HTML views that are retrieved by a SPA. Views may be dynamically generated on the server, and in situations where data doesn’t change often and can be shared across users, the views and data may be cached by the server to allow them to be served in a more efficient and scalable manner. Once views reach the client they can also be cached there of course for scenarios where a “fresh” view isn’t required each time a route is triggered. It also relieves load from the application, as well as make the application faster responsive.

Dynamic Views:

The server can once again be used to dynamically generate the view based upon specific security requirements. That way HTML fragments aren’t sent down to the client only to be hidden by the SPA framework based upon a user’s role. Only the view content that the authenticated and authorized user should see based upon their current roles/permissions is sent down to the browser.

Security:

Security is a key part of many applications. SPAs that load static HTML views from the server more than likely handle security on the client-side , as well as through the data service exposed by the server. What if your HTML view can easily compromise your application and data by simply changing client-side variables by a hacker? Browser development tools make it super easy to tweak HTML, CSS, and JavaScript so storing a user’s security roles. On the client is fine but every request to the server should be validated on the server-side to ensure that the user really does have a given role/permission and can perform a specific action. Otherwise, a hacker Using client-side code to secure applications is not a good way to go and arguably quite irresponsible.

For this reason i think that we should use server side scripting just not only to fasten the process but also put a extra layer of security to your applications.

In the above i tried to explain reasons for using server side scripting. But how can we accomplish that?
Let view that topic in the below.

In the below we are going to attempt to make a task manager, which will have features mentioned below.

  • Adding a task
  • Deleting a task
  • Managing a task’s status

To achieve this features we are going to need

  • Angular.js as front-end
  • php as backend
  • mysql as database

we are going to discuss only about angular.js and php. I leave the database on to you, so you can work with different data as you wish.

We will arrange the project files of our MVC framework into 5 different folders for better organisation.

  • js/ – Javascript library files. e.g. angular.js
  • app/ – Our custom javascript controller files for our project
  • partials/ – Small pagelets that we wish to reuse
  • ajax/ – The .php files to communicate to server (Connect, Create, Read, Update, Delete)
  • css/ – Stylesheet files

The Stylesheets:

Let us load some css for styling purpose

<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="css/taskman.css" rel="stylesheet" type="text/css" />

Importing javascript library:

<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="app/app.js"></script>

The Controller Code:

//Define an angular module for our app
var app = angular.module('myApp', []);

app.controller('tasksController', function($scope, $http) {
 getTask(); // Load all available tasks
 function getTask(){
 $http.get("ajax/getTask.php").success(function(data){
 $scope.tasks = data;
 });
 };
 $scope.addTask = function (task) {
 $http.get("ajax/addTask.php?task="+task).success(function(data){
 getTask();
 $scope.taskInput = "";
 });
 };
 $scope.deleteTask = function (task) {
 if(confirm("Are you sure to delete this line?")){
 $http.get("ajax/deleteTask.php?taskID="+task).success(function(data){
 getTask();
 });
 }
 };

$scope.toggleStatus = function(item, status, task) {
 if(status=='2'){status='0';}else{status='2';}
 $http.get("ajax/updateTask.php?taskID="+item+"&status="+status).success(function(data){
 getTask();
 });
 };

}); 

CRUD Files:

In the below we have the php files which accomplices the task for create,read,update and delete(CRUD) purpose

addTask.php

<?php
require_once '../includes/config.php'; // The mysql database connection script
if(isset($_GET['task'])){
$task = $_GET['task'];
$status = "0";
$created = time();

$query="INSERT INTO tasks(task,status,created_at) VALUES ('$task', '$status', '$created')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);

$result = $mysqli->affected_rows;

echo $json_response = json_encode($result);
}
?>

getTask.php

<?php
require_once '../includes/config.php'; // The mysql database connection script
$status = '%';
if(isset($_GET['status'])){
$status = $_GET['status'];
}
$query="select ID, TASK, STATUS from tasks where status like '$status' order by status,id desc";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);

$arr = array();
if($result->num_rows > 0) {
 while($row = $result->fetch_assoc()) {
 $arr[] = $row;
 }
}

# JSON-encode the response
echo $json_response = json_encode($arr);
?>

updateTask.php

<?php
require_once '../includes/config.php'; // The mysql database connection script
if(isset($_GET['taskID'])){
$status = $_GET['status'];
$taskID = $_GET['taskID'];
$query="update tasks set status='$status' where id='$taskID'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);

$result = $mysqli->affected_rows;

$json_response = json_encode($result);
}
?>

deleteTask.php

<?php
require_once '../includes/config.php'; // The mysql database connection script
if(isset($_GET['taskID'])){
$taskID = $_GET['taskID'];

$query="delete from tasks where id='$taskID'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);

$result = $mysqli->affected_rows;

echo $json_response = json_encode($result);
}
?>

In the above example is a one of the basic models for angular server side scripting. In this article i have just tried to put a basic idea on angular.js. That means server side scripting holds many features than this which are still to be understood.

We will launch a pdf about angular.js shortly where i’ll try to discuss about all the features of angular.js on a more detailed way.

Related Links:
1>Directive in Angular.js – Part 1
2>Directive in Angular.js – Part 2
3>Working with Modules in Angular.js
4>Angular Router and UI-Router
5>Angularjs and Services
6>Angular.js Promise
7>Angular.js Two Way Data Binding
8>How To Use Filter In Angular.js
9>Angular.js Event Handling
10>Using Controllers in Angular.Js
11>Working Through Angular.js With Transclude
12>Angular Templates

If you find this article helpful, you can connect us in Google+ and Twitter.