All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Form Validation Using Ajax And jQuery In PHP

Last Updated : Mar 11, 2024

Form Validation Using Ajax And jQuery In PHP

In this article we will show you the solution of form validation using ajax and jQuery in PHP, here first we need to create form then we have to does validation using jquery and then execute database connection to interact with database using ajax POST and inserts user filled details on table using insert query.

In form creation when they clicks submit then with the help of onclick event we submits form details to jquery code there we are checking each input fields details clearly then if they provided valid details which will inserted on database table otherwise we notifies user to provide valid details.

Step By Step Guide On Form Validation Using Ajax And Jquery In PHP :-

Here we imported three external files ‘open source bootstrap css cdn, jquery library, script file’ then we defined four input fields ‘Username, Email, Password, Confirm Password’ in form.

When user clicks submit button onclick event will triggers fun() function there we doing validation for each input fields separately if they provides valid detail then it stored on database table or we throwing error to notify user.

If user details are valid then using mysqli_connect() method we executed connection with database ‘dbase’ it refers ‘$con’ and then we storing user inputs on respective variables using POST statement.

We checking whether all inputs are not empty then we inserts all data to table ‘loginrec’ by definining insert query and it stored on variable ‘$sql’ then connection $con points insert query ‘$sql’. It will returns success message.

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="valid.js"></script>
</head>
<body class="bg-light">
<div class="container p-3">
<div class="col-lg-6 m-auto d-block p-3 bg-white">
<h2 class="pb-3 text-success">
                Form validation
</h2>
<div id="message"></div>
<form method="POST" id="myform">
<div class="row">
<div class="form-group col-md-6">
<label for="username">
                            Username:
</label>
<input type="text" name="username" id="username" class="form-control">
<span class="error" id="username_err"></span>
</div>
<div class="form-group col-md-6">
<label for="email">
                            Email:
</label>
<input type="email" name="email" id="email" class="form-control">
<span class="error" id="email_err"></span>
</div>
<div class="form-group col-md-12">
<label for="password">
                            Password:
</label>
<input type="password" name="password" id="password" class="form-control">
<span class="error" id="password_err"></span>
</div>
<div class="form-group col-md-12">
<label for="conpassword">
                            Confirm Password:
</label>
<input type="password" name="cpass" id="conpassword" class="form-control">
<span class="error" id="cpassword_err"></span>
</div>
<div class="col-md-12">
<button type="button" onclick="fun()" id="submitbtn" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
VALID.JS
function fun(){
$(document).ready(function () {
    if($('#username').val() != ''){
        checkuser();
    }
    else{
        $('#username_err').html('Please fill username!');
    }
    if($('#email').val() != ''){
        checkemail();
    }
    else{
        $('#email_err').html('Please fill email!');
    }
    if($('#password').val() != ''){
        checkpass();
    }
    else{
        $('#password_err').html('Please fill password!');
    }
    if($('#conpassword').val() != ''){
        checkcpass();
    }
    else{
        $('#cpassword_err').html('Please fill password!');
    }
    if(!checkuser() && !checkemail() && !checkpass() && !checkcpass()){
        $("#message").html("all fields required");
    }
    else{
            console.log("ok");
            $("#message").html("");
            var form = $('#myform')[0];
            var data = new FormData(form);
            $.ajax({
                type: "POST",
                url: "process.php",
                data: data,
                processData: false,
                contentType: false,
                cache: false,
                async: false,
                success: function (data) {
                    $('#message').html(data);
                },
                complete: function () {
                    setTimeout(function () {
                        $('#myform').trigger("reset");
                        $('#submitbtn').html('Submit');
                        $('#submitbtn').attr("disabled", false);
                        $('#submitbtn').css({ "border-radius": "4px" });
                    }, 50000);
                }
            });
        }
});
function checkuser() {
    var pattern = /^[A-Za-z]+$/;
    var user = $('#username').val();
    var validuser = user.match(pattern);
    if ($('#username').val().length < 4) {
        $('#username_err').html('username length is too short');
        return false;
    } else if (!validuser) {
        $('#username_err').html('username should be a-z ,A-Z only');
        return false;
    } else {
        $('#username_err').html('');
        return true;
    }
}
function checkemail() {
    var pattern1 = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var email = $('#email').val();
    var validemail = pattern1.test(email);
    if (email == "") {
        $('#email_err').html('required field');
        return false;
    } else if (!validemail) {
        $('#email_err').html('invalid email');
        return false;
    } else {
        $('#email_err').html('');
        return true;
    }
}
function checkpass() {
    var pattern2 = /^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
    var pass = $('#password').val();
    var validpass = pattern2.test(pass);
    if (pass == "") {
        $('#password_err').html('password can not be empty');
        return false;
    } else if (!validpass) {
        $('#password_err').html('Minimum 5 and upto 15 characters, at least one uppercase letter, one lowercase letter, one number and one special character:');
        return false;
    } else {
        $('#password_err').html("");
        return true;
    }
}
function checkcpass() {
    var pass = $('#password').val();
    var cpass = $('#conpassword').val();
    if (cpass == "") {
        $('#cpassword_err').html('confirm password cannot be empty');
        return false;
    } else if (pass !== cpass) {
        $('#cpassword_err').html('confirm password did not match');
        return false;
    } else {
        $('#cpassword_err').html('');
        return true;
}}}
PROCESS.PHP
<?php
$con = mysqli_connect("localhost", "root", "", "dbase");
if (!$con) {
    echo "connection error";
}
$name = htmlspecialchars(trim($_POST['username']));
$email = htmlspecialchars(trim($_POST['email']));
$pass = htmlspecialchars(trim($_POST['password']));
if (empty($name) || empty($email) || empty($pass)) {
    echo '<div class="alert alert-success">please fill all required field</div>';
} else {
    $sql = "insert into loginrec(UserName,Password,Email) values ('$name','$pass','$email')";
    if ($res = mysqli_query($con, $sql)) {
        echo '<div class="alert alert-success">data successfully inserted</div>';
    } else {
        echo '<div class="alert alert-warning">data not inserted</div>';
    }
}
?>
  1. A php script can be placed anywhere in the document. A php script starts with <?php and end with ?>.
  2. The default file extension for php files is “.php” and php statements end with ‘;’ semicolon.
  3. Here we needs to import three external files open source bootstrap css file will helps us for style form, ajax, jquery library support files helps us for validation and executes database connection using ajax POST and script file contains user defined validation in jquery.
  4. First we created html form with four fields ‘Username, Email, Password, Confirm Password’ with submit button it have onclick event there we declared fun() method. It will loads fun() function definition when user clicks on it and it’s defined in script valid.js file.
  5. Each input fields and forms defined with pre build bootstrap css classes which is helps us to style each of them quiclky. In valid.js file we defined fun() function there we defined ready() method for loads code when which is executed on browser.
  6. Within that we checking each input fields by referring input field id’s ‘#username, #username_err, #email_err, #email, #password, #password_err, #conpassword, #cpassword_err’.
  7. Using if condition we checking whether each input fields whether not null then we declaring respective function calls ‘checkuser(),checkemail(),checkpass(),checkcpass()’ or we appends respective error message on webpage.
  8. In checkuser() function definition we specifying characters only input pattern regular expressions and it is stored on variable ‘pattern’ then we checking whether user inputs match with pattern if they not matched then ‘username should be a-z ,A-Z only’ message will display.
  9. Then we checking user input length because we specified as needs minimum ‘username’ length will be above value 4 if they provide below that then ‘username length is too short’ message will thrown and if username is correct then it throws true with null string.
  10. In checkemail() function definition we specifying valid email pattern regular expressions and it is stored on variable ‘pattern1’ then we checking whether user inputs match with pattern if they not matched then ‘invalid email’ message will display.
  11. Then we checking user input of email whether empty or not then ‘required field’ message will thrown and if email is correct then it throws true with null string.
  12. In checkpass() function definition we specifying input pattern regular expressions contains ‘minimum 5 and maximum 15 then there atleasts of [one caps letter,one special character, one number must exists]’ and it is stored on variable ‘pattern2’ then we checking whether user inputs match with pattern if they not matched then ‘Minimum 5 and upto 15 characters,
  13. at least one uppercase letter, one lowercase letter, one number
  14. and one special character:’ message will display.
  15. Then we checking user input of password whether empty or not then ‘password cannot be empty’ message will thrown and if email is correct then it throws true with null string.
  16. In checkcpass() function definition we collecting password, confirm password inputs and it is stored on respective variables ‘pass,cpass’ then we comparing them whether both are same or not if they not same then ‘confirm password did not match’ message will display.
  17. Then we checking confirm password whether empty or not then ‘confirm password cannot be empty’ message will thrown and if email is correct then it throws true with null string.
  18. Finally we checking whether all methods return state it true or not using if condition if its true then on console we prints ‘ok’, success message appended on webpage, specifying form by id ‘#myform’.
  19. Using ajax we generates POST method with all input data to process them at process.php file. The success, complete are states when it reach this states then respective block of code will executed.
  20. If its meets success state then it will prints success message on html page or if its in complete state then it using setTimeout() method and resets form page it will happen after 50 secs.
  21. In process.php file we defined values ‘localhost,root,’’,’dbase’ for make connection with server database. Using mysqli_connect() method we executed database connection with those values and connection referred by variable ‘$con’.
  22. Then collected all input details stored on respective variables ‘$name, $email, $pass’ and using if condition we checking whether all are empty or not by empty() method. If they empty then ‘please fill all required field’ will display.
  23. Otherwise defined insert query with table name ‘loginrec’ for select all row values from table and it is stored on variable ‘$sql’.
  24. We know mysqli_query() method will executes query what we defined at database so we used this method for executes this select query at database by pointing with $con connection variable then it returns either all collected table records or null that is stored on variable ‘$res’.
  25. If executed query successfully then ‘data successfully inserted’ or ‘data not inserted’ message will displayed on webpage.

Conclusion :-

In conclusion now we are able to know how to validate form using ajax, jquery in php.

When work with php we need to create and process php files at server location and then we need to start the server before execute the program.

When we executing this program on browser we can see form with four input fields there user have to fill all fields then clicks on submit button if they valid then successfully inserted on database or it throws respective error message.

I hope this article on form validation using ajax and jQuery in PHP helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Amruta

Amruta is an Experienced web developer with 4 years for experience she completed her master's with MCA and passionate about programming Languages for creating technical contents like HTML, CSS, JavaScript, Java, Python, PHP, jQuery.

Follow Amruta On Linkedin 🡪