Ajax Form Validation With PHP

In this tutorial we will create a Ajax Form Validation With PHP. AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications. We will try to merge PHP as a serve side scripting for responding the request of the web browser. So let's see now. Creating A Database To create database, start by opening any kind of web server(wamp, xamp, etc...). After that go to phpmyadmin then click create database, and name the database as 'db_user'. Then after that click SQL, and copy/paste the code below then run the SQL statement.
  1. CREATE TABLE `user` (
  2. `userid` int(11) NOT NULL AUTO_INCREMENT,
  3. `username` varchar(30) NOT NULL,
  4. `password` varchar(30) NOT NULL,
  5. `firstname` varchar(50) NOT NULL,
  6. `lastname` varchar(50) NOT NULL,
  7. `email` varchar(100) NOT NULL
  8. PRIMARY KEY (`userid`)
Creating A Form To do that copy/paste the code below, then name it 'index.php'
  1. <!DOCTYPE html>
  2. <html lang = "en">
  3. <head>
  4. <meta charset = "UTF-8" name = "viewport" content = "width=device-width, initial-scale=1"/>
  5. <link rel = "stylesheet" type = "text/css" href = "css/bootstrap.css"/>
  6. <script src="js/ajax.js"></script>
  7. </head>
  8. <body>
  9. <nav class = "navbar navbar-default">
  10. <div class = "container-fluid">
  11. <a class = "navbar-brand" href = "https://sourcecodester.com">Sourcecodester</a>
  12. </div>
  13. </nav>
  14. <div class = "row">
  15. <div class = "col-md-4"></div>
  16. <div class = "col-md-4 well">
  17. <h3 class = "text-primary">Ajax Form Validation With PHP</h3>
  18. <hr style = "border-top:1px solid #000;"/>
  19. <form action = "query.php" method = "POST" id = "regForm">
  20. <div class = "form-group">
  21. <label>Username</label>
  22. <input id='username' class = "form-control" name='username' onblur="validate('username_result', this.value)" type='text' />
  23. <center><div id='username_result' class = "text-danger"></div><center>
  24. </div>
  25. <div class = "form-group">
  26. <label>Password</label>
  27. <input id='password' class = "form-control" name='password' onblur="validate('password_result', this.value)" type='password' />
  28. <center><div id='password_result' class = "text-danger"></div></center>
  29. </div>
  30. <div class = "form-group">
  31. <label>Firstname</label>
  32. <input id='firstname' class = "form-control" name='firstname' onblur="validate('firstname_result', this.value)" type='text' />
  33. <center><div id='firstname_result' class = "text-danger"></div></center>
  34. </div>
  35. <div class = "form-group">
  36. <label>Lastname</label>
  37. <input id='lastname' class = "form-control" name='lastname' onblur="validate('lastname_result', this.value)" type='text' />
  38. <center><div id='lastname_result' class = "text-danger"></div></center>
  39. </div>
  40. <div class = "form-group">
  41. <label>Email</label>
  42. <input id='email' class = "form-control" name='email' onblur="validate('email_result', this.value)" type='text' />
  43. <center><div id='email_result' class = "text-danger"></div><center>
  44. </div>
  45. <div class = "form-group">
  46. <button class = "btn btn-primary form-control" onclick="validForm()" name = "save" type='button'><span class = "glyphicon glyphicon-save"></span> Submit</button>
  47. </div>
  48. </form>
  49. </div>
  50. </div>
  51. </body>
  52. </html>
The code above will display the fill up form for the user. Creating Ajax Script To create this script, copy/paste the code below and name it 'ajax.js'.
  1. function validForm() {
  2. var name = document.getElementById("username").value;
  3. var password = document.getElementById("password").value;
  4. var firstname = document.getElementById("firstname").value;
  5. var lastname = document.getElementById("lastname").value;
  6. var email = document.getElementById("email").value;
  7. if (name == '' || password == '' || firstname == '' || lastname == '' ||email == '') {
  8. alert("Complete all the required fields");
  9. } else {
  10. var username1 = document.getElementById("username_result");
  11. var password1 = document.getElementById("password_result");
  12. var firstname1 = document.getElementById("firstname_result");
  13. var lastname1 = document.getElementById("lastname_result");
  14. var email1 = document.getElementById("email_result");
  15. if (username1.innerHTML == 'Must be 4+ letters' || password1.innerHTML == 'Password too short' || firstname1.innerHTML == 'Invalid' || lastname1.innerHTML == 'Invalid' || email1.innerHTML == 'Invalid email') {
  16. alert("Complete valid information");
  17. } else {
  18. document.getElementById("regForm").submit();
  19. }
  20. }
  21. }
  22.  
  23. function validate(field, value) {
  24. var xmlhttp;
  25. if (window.XMLHttpRequest) {
  26. xmlhttp = new XMLHttpRequest();
  27. } else {
  28. xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  29. }
  30.  
  31. xmlhttp.onreadystatechange = function() {
  32. if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
  33. document.getElementById(field).innerHTML = "Validating..";
  34. } else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  35. document.getElementById(field).innerHTML = xmlhttp.responseText;
  36. } else {
  37. document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
  38. }
  39. }
  40. xmlhttp.open("GET", "validation.php?field=" + field + "&value=" + value, true);
  41. xmlhttp.send();
  42. }
The code above will validate the input value of the user. The xmlhttp.open response to the server to fetch the data and validate if it is valid or invalid. Creating Validation This is where the warning message will show if the information is valid.
  1. <?php
  2. $val = $_GET['value'];
  3. $field = $_GET['field'];
  4.  
  5. if ($field == "username_result") {
  6. if (strlen($val) < 5) {
  7. echo 'Must be 4+ letters';
  8. } else {
  9. echo '<label class = "text-success">Valid</label>';
  10. }
  11. }
  12. if ($field == "password_result") {
  13. if (strlen($val) < 6) {
  14. echo 'Password too short';
  15. } else {
  16. echo '<label class = "text-success">Strong</label>';
  17. }
  18. }
  19.  
  20. if($field == "firstname_result"){
  21. if(strlen($val) < 2){
  22. echo 'Invalid';
  23. }else{
  24. echo '<label class = "text-success">Valid</label>';
  25. }
  26. }
  27.  
  28. if($field == "lastname_result"){
  29. if(strlen($val) < 2){
  30. echo 'Invalid';
  31. }else{
  32. echo '<label class = "text-success">Valid</label>';
  33. }
  34. }
  35.  
  36. if ($field == "email_result") {
  37. if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $val)) {
  38. echo 'Invalid email';
  39. } else {
  40. echo '<label class = "text-success">Valid</label>';
  41. }
  42. }
  43.  
  44. ?>
The code above will response to ajax and validate if the data meet the following requirements. Creating The Query This is where the data will be stored and then be send to the database server.
  1. <?php
  2. $conn = new mysqli("localhost", "root", "", "db_user") or die(mysqli_error());
  3. $username = $_POST['username'];
  4. $password = $_POST['password'];
  5. $firstname = $_POST['firstname'];
  6. $lastname = $_POST['lastname'];
  7. $email = $_POST['email'];
  8.  
  9. $stmt = $conn->prepare("INSERT INTO `user` (username, password, firstname, lastname, email) VALUES(?, ?, ?, ?, ?)");
  10. $stmt->bind_param("sssss", $username, $password, $firstname, $lastname, $email);
  11. if($stmt->execute()){
  12. $stmt->close();
  13. $conn->close();
  14. echo "<script>alert('Successfully Saved Records')</script>";
  15. echo "<script>window.location = 'index.php'</script>";
  16. }
  17.  
  18. ?>
The code above will store the value of the input into variable and then will be send to the database server. There you have it we created a ajax form validation with php. I hope that this tutorial give you some thoughts on how to implement ajax in your websites. For more updates and tutorials just kindly visit this site, don't forget to LIKE & SHARE. Enjoy Coding!!

Tags

Add new comment