Live Checking of Input Data Availability using VueJS and PHP Tutorial

In this tutorial, you will learn how to implement a Live Checking of Input Data Availability using VueJS and PHP. This tutorial aims to provide IT students and new programmers a reference for implementing a live interaction of an application between the client and server side using the said JS Framework and Programming Language. I have provided some snippets below for this tutorial. A sample web application source code file that demonstrates the objective of this tutorial is also provided and free to download.

How does Live Checking of Input Data Availability work?

Live Checking of Input Data Availability is one of the effective features of a web application. Some developers prefer to implement this kind of feature in some of their project forms. It allows the end-users or the form encoders to be notified right away if the data entered on the specific text field that requires a unique value is already existing. With this, end-users will know the availability status of the data immediately even if the form is not submitted yet.

How to implement or create a Live Checking of Input Data Availability using VueJS and PHP?

The Live Checking of Input Data Availability feature can be achieved in so many ways using PHP and Vue. Here are the following methods, functions, properties, and APIs of PHP and Vue that can help in implementing the said feature.

JavaScript

  • Vue methods
  • JS Fetch API
  • Vue Models
  • JS FormData

PHP

  • PHP MySQL OOP
  • MySQL SELECT Statement

To get a better understanding of how to use the given methods, functions, properties, and APIs of PHP and Vue above to implement a Live Checking of Input Data Availability feature, check out the snippets that I provided below. The snippets output a simple web application that inserts new employee records into the database.

Snippets

Database

The snippet that I provided uses a MySQL Database named dummy_db. The database has the following MySQL Schema.

  1. CREATE TABLE `employee_list` (
  2. `code` varchar(50) NOT NULL
  3. `name` varchar(250) NOT NULL
  4. `email` varchar(250) NOT NULL
  5. `department` varchar(250) NOT NULL
  6. `designation` varchar(250) NOT NULL

Database Connection

The following snippet is a PHP File named db-connect.php. The script handles the connection between the application and the database.

  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. }

Form Page Interface

The following snippet contains the script of the main page and the sample form interface. Save the file as 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>Check Input Data Availability | PHP & Vue.JS</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  10. <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>
  11. <script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>
  12. <style>
  13. html, body{
  14. min-height:100%;
  15. width:100%;
  16. }
  17. tbody:empty:after{
  18. content:'No records found'
  19. }
  20. </style>
  21. </head>
  22. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  23. <div class="container">
  24. <a class="navbar-brand" href="./">Check Input Data Availability</a>
  25. <div>
  26. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  27. </div>
  28. </div>
  29. </nav>
  30. <div class="container-fluid px-5 my-3" id="SampleApp">
  31. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  32. <h3 class="text-center"><b>Live Checking of Input Data Availability using PHP and Vue</b></h3>
  33. <div class="d-flex w-100 justify-content-center">
  34. <hr class="w-50">
  35. </div>
  36. <div class="card rounded-0 shadow mb-3">
  37. <div class="card-body">
  38. <div class="container-fluid">
  39. <div class="alert alert-success rounded-0 mb-3" v-show="is_success">{{success_message}}</div>
  40. <div class="alert alert-danger rounded-0 mb-3" v-show="is_error">{{error_message}}</div>
  41.  
  42. <form action="" id="sample-form" @submit="formSubmit">
  43. <div class="mb-3">
  44. <label for="code" class="form-label">Employee Code</label>
  45. <input type="text" id="code" name="code" v-model="code" @keyup="checkAvailability('code')" maxLength="50" class="form-control form-control-sm rounded-0" required>
  46. <div class="alert alert-danger rounded-0 mt-3" v-show="input_error.code.status">{{input_error.code.msg}}</div>
  47. <div class="alert alert-success rounded-0 mt-3" v-show="input_success.code.status">{{input_success.code.msg}}</div>
  48. </div>
  49. <div class="mb-3">
  50. <label for="name" class="form-label">Name</label>
  51. <input type="text" id="name" name="name" class="form-control form-control-sm rounded-0" required>
  52. </div>
  53. <div class="mb-3">
  54. <label for="email" class="form-label">Email</label>
  55. <input type="text" id="email" name="email" v-model="email" @keyup="checkAvailability('email')" class="form-control form-control-sm rounded-0" required>
  56. <div class="alert alert-danger rounded-0 mt-3" v-show="input_error.email.status">{{input_error.email.msg}}</div>
  57. <div class="alert alert-success rounded-0 mt-3" v-show="input_success.email.status">{{input_success.email.msg}}</div>
  58. </div>
  59. <div class="mb-3">
  60. <label for="department" class="form-label">Department</label>
  61. <input type="text" id="department" name="department" class="form-control form-control-sm rounded-0" required>
  62. </div>
  63. <div class="mb-3">
  64. <label for="designation" class="form-label">Desgination</label>
  65. <input type="text" id="designation" name="designation" class="form-control form-control-sm rounded-0" required>
  66. </div>
  67. </form>
  68. </div>
  69. </div>
  70. <div class="card-footer py-1 text-center">
  71. <button class="btn btn-primary rounded-pill col-lg-4 col-md-6 col-sm-12" form="sample-form">Save Employee</button>
  72. </div>
  73. </div>
  74. </div>
  75. </div>
  76. <script src="app.js"></script>
  77. </body>
  78. </html>

JavaScript

The snippet below is a JavaScript file that contains the script for initiating the VueJS. The methods of checking the input data availability and form submission are written in the snippet. Save it as app.js.

  1. const { createApp } = Vue
  2.  
  3. /**
  4.   * Create Vue App to the selected Element
  5.   */
  6. createApp({
  7. /**
  8.   * Application Data
  9.   */
  10. data() {
  11. return {
  12. is_error: false,
  13. is_success: false,
  14. success_message: "",
  15. error_message: "",
  16. code: '',
  17. email: '',
  18. input_error:{
  19. code:{status:false, msg:""},
  20. email:{status:false, msg:""}
  21. },
  22. input_success:{
  23. code:{status:false, msg:""},
  24. email:{status:false, msg:""}
  25. }
  26. }
  27.  
  28. },
  29. /**
  30.   * Application Methods
  31.   */
  32. methods:{
  33.  
  34.  
  35. /**
  36.   * Live Checking Input Data Availability Method
  37.   * @param {string} input
  38.   */
  39. checkAvailability(input){
  40. if(this[input] == '' || this[input] == null){
  41. this.input_error[input] = {status:false, msg:""}
  42. this.input_success[input] = {status:false, msg:""}
  43. return false;
  44. }
  45.  
  46. //Setting Form Data
  47. var fdata = new FormData();
  48. fdata.append(input,this[input])
  49. fdata.append("check_live",'true')
  50.  
  51. //Request for cheching input availability
  52. fetch("checkAvailability.php",{
  53. method:'POST',
  54. body: fdata
  55. })
  56. .then(response => response.json())
  57. .then(data=>{
  58. if(!!data.status){
  59. if(data.status == 'success'){
  60. if(!!data.success){
  61. //Return Success Message
  62. Object.keys(data.success).map(k => {
  63. this.input_success[k] = data.success[k]
  64. this.input_error[k] = {status:false, msg: ''}
  65. })
  66. }
  67. if(!!data.error){
  68. //Return Error Message
  69. Object.keys(data.error).map(k => {
  70. this.input_error[k] = data.error[k]
  71. this.input_success[k] = {status:false, msg: ''}
  72. })
  73. }
  74. }
  75. }
  76. })
  77. .catch(error=>{
  78. console.error(error)
  79. })
  80. },
  81. formSubmit(e){
  82. e.preventDefault();
  83.  
  84. //Submitted Form
  85. var form = e.target
  86.  
  87. // Setting New Form Data
  88. var fdata = new FormData(form);
  89.  
  90. // Chech some Availability Error before saving the record
  91. if(this.input_error.code.status || this.input_error.email.status){
  92. is_error = true
  93. error_message= "Some of the input data are already exists."
  94. }
  95.  
  96.  
  97. // Request for Saving the record
  98. fetch("saveEmployee.php",{
  99. method:'POST',
  100. body: fdata
  101. })
  102. .then(response => response.json())
  103. .then(data=>{
  104. if(!!data.status){
  105. if(data.status == 'success'){
  106. // If the request process is successful
  107. form.reset();
  108. this.is_success = true;
  109. this.is_error = false;
  110. this.code = "";
  111. this.email = "";
  112. if(!!data.msg){
  113. this.success_message = data.msg
  114. }
  115. this.input_error={
  116. code:{status:false, msg:""},
  117. email:{status:false, msg:""}
  118. },
  119. this.input_success={
  120. code:{status:false, msg:""},
  121. email:{status:false, msg:""}
  122. }
  123. }else{
  124. // If the request process has failed to continue
  125. this.is_success = false;
  126. if(!!data.error){
  127. Object.keys(data.error).map(k => {
  128. this.input_success[k] = {status:false, msg: ''}
  129. this.input_error[k] = data.error[k]
  130. })
  131. }
  132. if(!!data.msg){
  133. this.is_error = true;
  134. this.error_message = data.msg
  135. }
  136. }
  137. }
  138. })
  139. .catch(error=>{
  140. console.error(error)
  141. })
  142.  
  143. }
  144. }
  145. }).mount('#SampleApp')

Check Availability API

Here is the snippet of a PHP File that contains the PHP Script for checking the availability of the entered input value of the end user. The script will be executed using the checkAvailability() method on the Vue App script. The script will be used also before the insertion process to check the availability again before executing the insertion of data on the database. Save it as checkAvailability.php.

  1. <?php
  2. include_once('db-connect.php');
  3.  
  4. function check_availability(){
  5. global $conn;
  6. // Allowed fields to check
  7. $allowed_fields = ['code', 'email'];
  8. $response['status'] = 'success';
  9.  
  10. /**
  11.   * Dynamically checking the input data availablity
  12.   */
  13. foreach($_POST as $k => $v){
  14. if(in_array($k, $allowed_fields)){
  15. $v = $conn->real_escape_string(trim($v));
  16.  
  17. // SQL Statement
  18. $check_sql = "SELECT id FROM `employee_list` where `{$k}` = '{$v}' ";
  19. // SQL Query
  20. $check_qry = $conn->query($check_sql);
  21.  
  22. if($check_qry->num_rows > 0){
  23. // If data does not exists yet
  24. $response['error'][$k]['status'] = 'true';
  25. $response['error'][$k]['msg'] = "The entered {$k} already exists.";
  26. }else{
  27. // If data already exists
  28. $response['success'][$k]['status'] = 'true';
  29. $response['success'][$k]['msg'] = "The entered {$k} is still avalailable.";
  30.  
  31. }
  32. }
  33. }
  34. return $response;
  35. }
  36.  
  37. if(isset($_POST['check_live']) && $_POST['check_live'] == 'true'){
  38. // If request was executed upon input keyup event
  39. echo json_encode(check_availability());
  40. $conn->close();
  41. }
  42.  
  43. ?>

Data Insertion API

The following snippet is PHP Script that contains the script for inserting the form's input data values on the database. The script loads the checkAvailability.php file for validating the input value availability before the execution of insertion. Save the file saveEmployee.php.

  1. <?php
  2. require_once('db-connect.php');
  3. require_once('checkAvailability.php');
  4.  
  5. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  6. /**
  7.   * Check input availability before saving
  8.   */
  9. $input_check = check_availability();
  10. if(isset($input_check['error'])){
  11.  
  12. // If some data already exists
  13. $input_check['status'] = 'error';
  14. $input_check['msg'] = "Some of the input data already exists.";
  15. echo json_encode($input_check);
  16.  
  17. }
  18.  
  19. // sanitizing input values
  20. foreach($_POST as $k => $v){
  21. $$k = addslashes($conn->real_escape_string($v));
  22. }
  23.  
  24. // Insert SQL Statement
  25. $sql = "INSERT INTO `employee_list`
  26. (`code`, `name`, `email`, `department`, `designation`)
  27. VALUES
  28. ('{$code}','{$name}','{$email}','{$department}','{$designation}')
  29. ";
  30.  
  31.  
  32. // Insert SQL Query
  33. $insert = $conn->query($sql);
  34.  
  35. if($insert){
  36. // If insertion is successful
  37. $response['status'] = 'success';
  38. $response['msg'] = 'New Employee Data has been added successfully.';
  39. }else{
  40. // If insertion has failed
  41. $response['status'] = 'success';
  42. $response['msg'] = 'Employee Data has failed to insert. Error: '.$conn->error;
  43. }
  44.  
  45. echo json_encode($response);
  46. }
  47.  
  48. $conn->close();

That's it! You can now test the sample web application on your end and see if it achieves the objective of this tutorial. I have provided also the source code zip file on this article. You can download it by clicking the Download Button below this article.

Snapshots

Here are some of the snapshots of the application's output.

Form Interface

Live Checking of Input Data using PHP and VueJS

Input Data Availability Message (Available)

Live Checking of Input Data using PHP and VueJS

Input Data Availability Message (Existing)

Live Checking of Input Data using PHP and VueJS

Form's Interface with Alerts

Live Checking of Input Data using PHP and VueJS

That's the end of this tutorial. I hope this Live Checking of Input Data Availability using VueJS and PHP Tutorial helps you with what you are looking for and that you'll find this useful for your current and future projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding:)

Add new comment