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:

  1. <div ng-controller="MyFormController">
  2. ....
  3. </div>

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.

  1. <div ng-controller="MyFormController">
  2. <form ng-submit="saveData()">
  3. ......
  4. </form>
  5. </div>

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.

  1. var app = angular.module("MyApp",[]);
  2.  
  3. mymodule.controller("TestController", function ($scope, $http){
  4. $scope.saveData = function (){
  5.  
  6. $http.post("saveData.php", $scope.model).then(function success(response){
  7. //Do anything after succesfull request
  8. }, function error(response){
  9. //Do anything after an error occurred in the request
  10. });
  11. };
  12. })

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

  1. $data = json_decode(file_get_contents("php://input"));
  2.  
  3. if(!isset($data->name) || (isset($data->name) && empty($data->name))){
  4. $name_error = "Name field is required.";
  5. }
  6. if(isset( $name_error)){
  7. echo json_encode(['status' => 'failed', 'error' => $name_error]);
  8. }else{
  9. // Do anything here [Form data is validated]
  10. echo json_encode(['status' => 'success']);
  11. }

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

  1. CREATE TABLE `members` (
  2. `first_name` varchar(250) NOT NULL,
  3. `middle_name` varchar(250) NOT NULL,
  4. `last_name` varchar(250) NOT NULL,
  5. `email` varchar(250) NOT NULL,
  6. `contact` varchar(50) NOT NULL

Database Connection

db-connect.php

  1. <?php
  2. $host = "localhost";
  3. $username = "root";
  4. $pw = "";
  5. $db_name = "dummy_db";
  6.  
  7. $conn = new mysqli($host, $username, $pw, $db_name);
  8.  
  9. if(!$conn){
  10. die("Database Connection Failed");
  11. }

Interface

index.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Form Submission w/ Validation</title>
  7. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  8. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.js" integrity="sha512-klc+qN5PPscoGxSzFpetVsCr9sryi2e2vHwZKq43FdFyhSAa7vAqog/Ifl8tzg/8mBZiG2MAKhyjH5oPJp65EA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  9. <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>
  10. html, body{
  11. min-height:100%;
  12. width:100%;
  13. }
  14. .img-holder {
  15. text-align: center;
  16. height: 20vw;
  17. border: 1px solid;
  18. width: 100%;
  19. display: flex;
  20. justify-content: center;
  21. align-items: center;
  22. background: black;
  23. }
  24. .img-holder > img{
  25. max-height:calc(100%);
  26. max-width:calc(100%);
  27. object-fit:scale-down;
  28. object-position:center center;
  29. }
  30. </style>
  31. </head>
  32. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  33. <div class="container">
  34. <a class="navbar-brand" href="./">Form Submission w/ Validation using PHP and Angular.JS</a>
  35. <div>
  36. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  37. </div>
  38. </div>
  39. </nav>
  40. <div class="container-fluid px-5 my-3">
  41. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  42. <div class="card rounded-0 shadow" ng-app="SampleApp" ng-controller="TestController">
  43. <div class="card-body">
  44. <div class="container-fluid">
  45. <form ng-submit="formSubmit()">
  46. <div class="alert alert-success mb-3" ng-show="success_msg">{{success_msg}}</div>
  47. <div class="alert alert-danger mb-3" ng-show="error_msg">{{error_msg}}</div>
  48. <div class="mb-3">
  49. <label for="first_name" class="form-label">First Name</label>
  50. <input type="text" class="form-control rounded-0" id="first_name" ng-model="model.first_name" name="first_name">
  51. <div class="alert alert-danger rounded-0 mt-2" ng-show="err_first_name">{{err_first_name}}</div>
  52. </div>
  53. <div class="mb-3">
  54. <label for="middle_name" class="form-label">Middle Name</label>
  55. <input type="text" class="form-control rounded-0" id="middle_name" ng-model="model.middle_name" name="middle_name">
  56. </div>
  57. <div class="mb-3">
  58. <label for="last_name" class="form-label">Last Name</label>
  59. <input type="text" class="form-control rounded-0" id="last_name" ng-model="model.last_name" name="last_name">
  60. <div class="alert alert-danger rounded-0 mt-2" ng-show="err_last_name">{{err_last_name}}</div>
  61. </div>
  62. <div class="mb-3">
  63. <label for="email" class="form-label">Email</label>
  64. <input type="text" class="form-control rounded-0" id="email" ng-model="model.email" name="email">
  65. <div class="alert alert-danger rounded-0 mt-2" ng-show="err_email">{{err_email}}</div>
  66. </div>
  67. <div class="mb-3">
  68. <label for="contact" class="form-label">Contact #</label>
  69. <input type="text" class="form-control rounded-0" id="contact" ng-model="model.contact" name="contact">
  70. <div class="alert alert-danger rounded-0 mt-2" ng-show="err_contact">{{err_contact}}</div>
  71. </div>
  72. <div class="mb-3 d-grid">
  73. <button type="submit" class="btn btn-primary btn-block rounded-pill">Register</button>
  74. </div>
  75. </form>
  76. </div>
  77. </div>
  78. </div>
  79. </div>
  80. </div>
  81. <script src="app.js"></script>
  82. </body>
  83. </html>

JavaScript

app.js

  1. var mymodule = angular.module("SampleApp",[]);
  2.  
  3. mymodule.controller("TestController", function ($scope, $http){
  4. $scope.formSubmit = function(){
  5. $scope.err_first_name = null
  6. $scope.err_last_name = null
  7. $scope.err_email = null
  8. $scope.err_contact = null
  9. $scope.error_msg = null
  10. $scope.success_msg = null
  11. $http.post("insertData.php", $scope.model).then(function success(response){
  12. console.log('success', response.data.status)
  13. if(response.data.status == 'success'){
  14. $scope.success_msg = "New Data has been added successfully";
  15. document.querySelector('form').reset()
  16. }else if(response.data.status == 'error'){
  17. if(!!response.data.errors.err_first_name)
  18. $scope.err_first_name = response.data.errors.err_first_name;
  19. if(!!response.data.errors.err_last_name)
  20. $scope.err_last_name = response.data.errors.err_last_name;
  21. if(!!response.data.errors.err_email)
  22. $scope.err_email = response.data.errors.err_email;
  23. if(!!response.data.errors.err_contact)
  24. $scope.err_contact = response.data.errors.err_contact;
  25. if(!!response.data.errors.error_msg)
  26. $scope.error_msg = response.data.errors.error_msg;
  27. }else{
  28. $scope.error_msg = "Failed to insert data due to some unknown reason.";
  29. }
  30. }, function error(response){
  31. console.log('error', response)
  32. });
  33. };
  34. })

PHP

insertData.php

  1. <?php
  2. require_once("db-connect.php");
  3. // Data
  4. $data = (array) json_decode(file_get_contents("php://input"));
  5.  
  6. // sanitizing data
  7. $first_name = trim(addslashes($conn->real_escape_string($data['first_name'] ?? "")));
  8. $middle_name = trim(addslashes($conn->real_escape_string($data['middle_name'] ?? "")));
  9. $last_name = trim(addslashes($conn->real_escape_string($data['last_name'] ?? "")));
  10. $email = trim(addslashes($conn->real_escape_string($data['email'] ?? "")));
  11. $contact = trim(addslashes($conn->real_escape_string($data['contact'] ?? "")));
  12.  
  13. /**
  14. * Validate Input Data
  15. */
  16. $errors = [];
  17. //first_name validation
  18. if(empty($first_name))
  19. $errors['err_first_name'] = "First Name is a required field";
  20.  
  21. //last_name validation
  22. if(empty($last_name))
  23. $errors['err_last_name'] = "Last Name is a required field";
  24.  
  25.  
  26. //Email validation
  27. if(empty($email))
  28. $errors['err_email'] = "Email is a required field";
  29. elseif(!(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,10})$/', $email)))
  30. $errors['err_email'] = "Invalid Email";
  31.  
  32. //Email Contact
  33. if(empty($contact))
  34. $errors['err_contact'] = "Contact is a required field";
  35. elseif(!(preg_match('/^09([0-9]{9})/', $contact)))
  36. $errors['err_contact'] = "Invalid Contact. Must start with 09 and must be 11 numbers.";
  37.  
  38. if(count($errors) > 0){
  39. $response = ['status' => 'error', 'errors' => $errors];
  40. }else{
  41. /**
  42.   * Save Data After the successfull validation
  43.   */
  44. $sql = "INSERT INTO `members` (`first_name`, `middle_name`, `last_name`, `email`, `contact`) VALUES ('{$first_name}', '{$middle_name}', '{$last_name}', '{$email}', '{$contact}')";
  45. $insert = $conn->query($sql);
  46. if($insert){
  47. $response = ["status" => 'success'];
  48. }else{
  49. $response = ['status' => 'error', 'errors' => ["error_msg" => "There's an error occurred while saving the data. Error: ".$conn->error]];
  50.  
  51. }
  52. }
  53.  
  54. // Return Response
  55. echo json_encode($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