Skip to main content

How to insert in Mysql with Jquery Ajax with validation?

By November 2, 2011Jquery
Using of this tutorials you can easily Insert data in database and validate your form using jquery.

Create ajax.php file


    mysql_connect(“localhost”, “root”, “”)or die(“cannot connect”);
    mysql_select_db(“prodchecklist”)or die(“cannot select DB”);   
    $fname        = htmlspecialchars(trim($_POST[‘fname’])); 
    $lname        = htmlspecialchars(trim($_POST[‘lname’])); 
    $addClient  = “INSERT INTO tbluser (username,userpassword) VALUES (‘$fname’,’$lname’)”; 
    mysql_query($addClient) or die(mysql_error()); 


        <script src=”lib/jquery/jquery-1.3.2.js” type=”text/javascript”>
        <script src=”javascripts/jquery.validate.js” type=”text/javascript”>
        <script type=”text/javascript”>
                $(“form#submit”).submit(function() {
                $(“#loader”).fadeIn(400).html(‘<img src=”ajax-loader.gif” align=”absmiddle”>&nbsp;<span class=”loading”>Loading Comment…</span>’);
                 var hasError = false;  
                // we want to store the values from the form input box, then send via ajax below
                var fname     = $(‘#fname’).attr(‘value’);
                var lname     = $(‘#lname’).attr(‘value’);          
                if(fname == ”){
                     $(“#fname”).after(‘<span class=”error”>Please enter a First name</span>’);                    
                    hasError = true;
                if(lname == ”){
                     $(“#lname”).after(‘<span class=”error”>Please enter a Last name</span>’);
                     hasError = true;
                    if(hasError = false){
                            type: “POST”,
                            url: “ajax.php”,
                            data: “fname=”+ fname +”& lname=”+ lname,
                            success: function(){
                return false;
        <div class=”container”>
            <form id=”submit” method=”post”>
                    <legend>Enter Information</legend>

                    <label for=”fname”>Client First Name:</label>
                    <input id=”fname” class=”text” name=”fname” size=”20″ type=”text”>
                    <label for=”lname”>Client Last Name:</label>
                    <input id=”lname” class=”text” name=”lname” size=”20″ type=”text”>
                    <button class=”button positive”> Add Client </button>
        <div class=”success” style=”display: none;”>Client has been added.</div>
        <div id=”loader” align=”left”></div>


Leave a Reply

7 + 2 =

Open chat
💬 Need help?
Hello 👋
We are expert at building website and digital properties. Do you have an idea that you want to bring to life. Let us know and we will build it for you.