How to get the Angular Posted Request in PHP

https://angularjs.org/

The POST method which angular uses send data using JSON format and in PHP Script we will not be able to receive POST data by simply writting $_POST directly.

I am assuming that you have read basic angularjs tutorial and know how to setup angular project.

Create a new angular controller and attach it to your project using

// the file should be relative to your html file
<script src="org_controller.js"></script>

Now let’s create our basic form in HTML to add an organization name and description.

<form name="frmAddOrg" class="form-horizontal" ng-submit="frmAddOrg.$valid && submitAddOrganization()" novalidate>
<div class="form-group">
    <label class="col-sm-3 control-label no-padding-right" for="form-field-name">Name <i class="red ace-icon fa fa-asterisk smaller-60 align-top"></i></label> 
    <div class="col-sm-9">
        <div class="clearfix">
            <input type="text" class="col-sm-12" maxlength="255" name="new_organization_name" id="new_organization_name" ng-model="new_organization_name" value="" placeholder="Name" ng-minlength="5" ng-maxlength="255" autofocus required />
        </div> 

        <div class="has-error" ng-show="frmAddOrg.new_organization_name.$dirty && frmAddOrg.new_organization_name.$invalid">
            <small class="help-block" ng-show="frmAddOrg.new_organization_name.$error.required">
                Organization name is required.
            </small>
            <small class="help-block" ng-show="frmAddOrg.new_organization_name.$error.minlength">
                Organization name is required to be at least 5 characters
            </small>
            <small class="help-block" ng-show="frmAddOrg.new_organization_name.$error.maxlength">
                Organization name cannot be longer than 255 characters
            </small>
        </div> 
    </div>
</div> 

<div class="form-group">
    <label class="col-sm-3 control-label no-padding-right" for="form-field-description">Description</label> 
    <div class="col-sm-9">
        <div class="clearfix"> 
            <textarea name="description" id="description" ng-model="description" class="col-sm-12" ng-minlength="5" ng-maxlength="1255" >{$description}</textarea>
        </div> 

        <div class="error help-block" ng-show="frmAddOrg.description.$dirty && frmAddOrg.description.$invalid"> 
            <small class="error" ng-show="frmAddOrg.description.$error.minlength">
                Organization Description is required to be at least 5 characters
            </small>
            <small class="error" ng-show="frmAddOrg.description.$error.maxlength">
                Organization Description cannot be longer than 1255 characters
            </small>
        </div> 
    </div>
</div> 



<div class="clearfix">
    <div class="col-md-offset-3 col-md-9">
        <button class="btn btn-info btn-minier btn-round" type="submit" ng-disabled="frmAddOrg.$invalid">
            <i class="ace-icon fa fa-check"></i>
            Submit
        </button>
        <button type="reset" class="btn btn-minier btn-round">
            <i class="ace-icon fa fa-undo"></i>
            Reset
        </button> 
        <button ng-click="hide_add_organization_container()" type="button" class="btn btn-info btn-minier btn-round back">
            <i class="ace-icon fa fa-reply"></i>
            Cancel
        </button>  
    </div>
</div>  
</form>  

We have named our angular app as “organizationTreeApp” and controller as “organizationTreeCtrl”. Let’s create our org_controller.js file to initialize angular app. Create file name as org_controller.js and put this code in it.

(function() {
    'use strict';
    /* Controllers */ 
    var organizationControllers = angular.module('organizationTreeApp', ['ui.tree']);

    organizationControllers.controller('organizationTreeCtrl', ['$scope', '$http',
        function ($scope, $http) {  
             
            // Add organization submit handler
            $scope.submitAddOrganization = function() { 
                console.log('called submit');

                var params = {'name':this.new_organization_name, 'description': this.description};
                $http.post('add_organization', JSON.stringify(params)).
                    success(function(data, status, headers, config, statusText) { 
                        $scope.message = data;

                        // If you are adding the organization from the same page where the organizations are listed, Add the new added organization in json list to appear on the same page.

                        $scope.msg_success = data.message; 
                        var new_item = {'id':data.id, 'title':params.name, 'desc': params.description, 'type': 'org', 'items': {}};
                        $scope.list.push(new_item);
                        $scope.new_organization_name = '';
                        $scope.description = '';  

                    }).
                    error(function(data, status, headers, config, statusText) { 
                        alert( "failure message: " + JSON.stringify({data: data}));
                    }
                ); 
            };   

        }
    ]);  
})();

Now we have to read POST data in PHP sent from Angular.

/** 
 * add_organization  
 *  
 * 
 * @access public 
 * @param  
 * @return   
 */

public function add_organization()
{  
	/*
	 * Collect all Details from Angular HTTP Request.
	 */ 
	$angular_posted_data = file_get_contents("php://input");
	$post_data_object = json_decode($angular_posted_data);

	$post_data = array( 
		'name' => $post_data_object->name, 
		'description' => $post_data_object->description
	);

	$post_data['created_by_id'] = $this->session->userdata('id');
	$id = $this->organizations_model->add($post_data);
	if($id !== FALSE && is_numeric($id))
	{
		$return = array('id' => $id, 'message' => $this->lang->line('organizations_add_success_message')); 
	}
	else
	{
		$return = array('id' => 0, 'message' => $this->lang->line('organizations_add_error_message')); 
	}
	echo json_encode($return);
	exit();
}

Leave a Reply

Your email address will not be published. Required fields are marked *