Submitting Form Data using Angular JS and PHP Tutorial
Introduction
In this tutorial, we will tackle about how to submit form data with validation using AngularJS and PHP. The tutorial aims to provide students and new programmers a reference to learn with for enhancing their programming capabilities using AngularJS and PHP Language. Here, snippets and source codes will be provided to give you a better understanding of the topic.
What is AngularJS?
AngularJS is a structural framework for dynamic web applications. It enables you to use HTML as your template language and enhance HTML's syntax to represent the components of your application simply and plainly. Data binding and dependency injection in AngularJS allow you to write a lot less code than you would otherwise. And since everything takes place within the browser, any server technology can work well with it.
How to Submit form Data using AngularJS?
Submitting your form data using AngularJS is not that complicated. You can achieve this by adding a ngController (a directive in module ng) by adding it into your template or HTML element's attribute such as below:
And, using the ngSubmit (a directive in module ng) in your form element. This directive enables you to bind with the submit event. Using this, you can add an Angular expression to trigger a function for processing the form data. See the following snippet below.
The above snippets demonstrate that the saveData() expression will be triggered when submitting the form. Then, you can handle your input validation in PHP by sending them a request to a PHP file using the $http service of AngularJS. It facilitates communication with the remote server via the browser's XMLHttpRequest.
- var app = angular.module("MyApp",[]);
- mymodule.controller("TestController", function ($scope, $http){
- $scope.saveData = function (){
- $http.post("saveData.php", $scope.model).then(function success(response){
- //Do anything after succesfull request
- }, function error(response){
- //Do anything after an error occurred in the request
- });
- };
- })
To process your input validation in PHP, you can use file_get_contents("php://input") to get the form data that was submitted using the AngularJS $http service. Then you can create your logic for validation for each input data. Here's the following example
- $name_error = "Name field is required.";
- }
- }else{
- // Do anything here [Form data is validated]
- }
The form validation will depend on how your application must work or the logic must be aligned to your application requirements. The given snippets only demonstrate how you can achieve the process using the AngularJS and PHP Language.
Example Application
Here's an example application source code that demonstrates our goal or topic for this tutorial. The application is a simple registration form that requires the users to fill in all the required fields and give the corresponding pattern accepted for some fields such as the email field.
Create a new Database named dummy_db and use the following MySQL Schema and Database Connection.
MySQL
Database Connection
db-connect.php
- <?php
- $host = "localhost";
- $username = "root";
- $pw = "";
- $db_name = "dummy_db";
- $conn = new mysqli($host, $username, $pw, $db_name);
- if(!$conn){
- }
Interface
index.php
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
- <style>
- html, body{
- min-height:100%;
- width:100%;
- }
- .img-holder {
- text-align: center;
- height: 20vw;
- border: 1px solid;
- width: 100%;
- display: flex;
- justify-content: center;
- align-items: center;
- background: black;
- }
- .img-holder > img{
- max-height:calc(100%);
- max-width:calc(100%);
- object-fit:scale-down;
- object-position:center center;
- }
- </style>
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div class="container-fluid px-5 my-3">
- <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
- <div class="card rounded-0 shadow" ng-app="SampleApp" ng-controller="TestController">
- <div class="card-body">
- <div class="container-fluid">
- <form ng-submit="formSubmit()">
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="first_name" ng-model="model.first_name" name="first_name">
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="middle_name" ng-model="model.middle_name" name="middle_name">
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="last_name" ng-model="model.last_name" name="last_name">
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="email" ng-model="model.email" name="email">
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="contact" ng-model="model.contact" name="contact">
- </div>
- <div class="mb-3 d-grid">
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
JavaScript
app.js
- var mymodule = angular.module("SampleApp",[]);
- mymodule.controller("TestController", function ($scope, $http){
- $scope.formSubmit = function(){
- $scope.err_first_name = null
- $scope.err_last_name = null
- $scope.err_email = null
- $scope.err_contact = null
- $scope.error_msg = null
- $scope.success_msg = null
- $http.post("insertData.php", $scope.model).then(function success(response){
- console.log('success', response.data.status)
- if(response.data.status == 'success'){
- $scope.success_msg = "New Data has been added successfully";
- document.querySelector('form').reset()
- }else if(response.data.status == 'error'){
- if(!!response.data.errors.err_first_name)
- $scope.err_first_name = response.data.errors.err_first_name;
- if(!!response.data.errors.err_last_name)
- $scope.err_last_name = response.data.errors.err_last_name;
- if(!!response.data.errors.err_email)
- $scope.err_email = response.data.errors.err_email;
- if(!!response.data.errors.err_contact)
- $scope.err_contact = response.data.errors.err_contact;
- if(!!response.data.errors.error_msg)
- $scope.error_msg = response.data.errors.error_msg;
- }else{
- $scope.error_msg = "Failed to insert data due to some unknown reason.";
- }
- }, function error(response){
- console.log('error', response)
- });
- };
- })
PHP
insertData.php
- <?php
- require_once("db-connect.php");
- // Data
- // sanitizing data
- /**
- * Validate Input Data
- */
- $errors = [];
- //first_name validation
- $errors['err_first_name'] = "First Name is a required field";
- //last_name validation
- $errors['err_last_name'] = "Last Name is a required field";
- //Email validation
- $errors['err_email'] = "Email is a required field";
- elseif(!(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,10})$/', $email)))
- $errors['err_email'] = "Invalid Email";
- //Email Contact
- $errors['err_contact'] = "Contact is a required field";
- $errors['err_contact'] = "Invalid Contact. Must start with 09 and must be 11 numbers.";
- $response = ['status' => 'error', 'errors' => $errors];
- }else{
- /**
- * Save Data After the successfull validation
- */
- $sql = "INSERT INTO `members` (`first_name`, `middle_name`, `last_name`, `email`, `contact`) VALUES ('{$first_name}', '{$middle_name}', '{$last_name}', '{$email}', '{$contact}')";
- $insert = $conn->query($sql);
- if($insert){
- $response = ["status" => 'success'];
- }else{
- $response = ['status' => 'error', 'errors' => ["error_msg" => "There's an error occurred while saving the data. Error: ".$conn->error]];
- }
- }
- // Return Response
That's it! You can now test the sample application on your end. You can also download the complete working source code of the sample application I provided by downloading the zip file. The download button can be found below this article.
DEMO VIDEO
That's the end of this tutorial. I hope this AngularJS and PHP Tutorial will help you with what you are looking for and that you'll find this useful for your current and future web application projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :)
Add new comment
- 428 views