Form validation with AJAX return

    |
  • Added:
  • |
  • In: Wordpress

I have a contact form that, when submit is clicked, I want to be validated.

If all fields return valid, then I want AJAX to return a Processing message, then, when successful, a message appears with the imputed name.

My Form content is:

<form onsubmit="return validateForm">
<input id="fname" class="textbox" name="fname" placeholder="First Nname" type="text" required="required" /><p>
<input id="sname" class="textbox" name="sname" placeholder="Surname" type="text" required="required" /><p>
<input id="email" class="textbox" name="email" placeholder="Email Address" type="email" required="required" /><p>
<input id="number" class="textbox" name="number" placeholder="Contact Number" type="email" /><p>
<textarea rows="10" id="message" class="textarea" name="message" placeholder="Message" required="required" ></textarea><p>
<input fname="myBtn" class="button" type="submit" value="Submit" onClick="javascript:ajax_post();">

My Form Validation content is:

function validateForm()
{
var fname=document.forms["Form"]["fname"].value;
var sname=document.forms["Form"]["sname"].value;
var x=document.forms["Form"]["email"].value;
var telnum=document.forms["Form"]["telnum"].value;
var message=document.forms["Form"]["message"].value;

if(fname==null||fname=="")
    {
    alert("please enter your first name");
    return false;
    }

if(sname==null||sname=="")
    {
    alert("please enter your surname");
    return false;
    }

var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if(atpos<1||dotpos<atpos+2||dotpos+2>x.lenght)
    {
    alert("Not a valid email address.");
    return false;
    }

if(message==null||message=="")
    {
    alert("please enter a message");
    return false;
    }
}

The AJAX Script is:

function ajax_post(){
var hr = new XMLHttpRequest();
var url = "/additional/formfeedback.php";
var fname = document.getElementById("fname").value;
var vars = "fname="+fname;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "Processing...";
}

And the returned PHP is:

<?php 
echo 'Thank you '. $_POST['fname'] . ', we have recieved your message and will be back in touch shortly';
?>

When the Submit button is clicked, the PHP content is returned, then the validation starts - obviously too late.

How do I get this to validate correctly, then carry out the AJAX script? I don't want to use any additional libraries, such a jQuery. Thanks in advance.

This Question Has 6 Answeres | Orginal Question | Conrad M

One point ... you don't need "javascript:" in an onclick. It's already expecting javascript.

Also, if you want to submit data with Ajax, change the button to type="button" (not submit)

Call ajax_post at the end of your validateForm method.

<script type="text/javascript">

        $(document).ready(function(){
            $("#submit").click(function(){

                var fname  = $("#fname").val();
                var lname  = $("#lname").val();
                var email   = $("#email").val();
                var password = $("#Password").val();
                var cpassword = $("#cpassword").val();
                var gender = $("input[name=gender]:checked").val();
                var dob    = $("#dob").val();
                var image  = $("#image").val();
                var status  = $("#status").val();
                var submit  = $("#submit").val();

             var dataString='fname='+fname+'&lname='+lname+'&email='+email+ '&password='+password+ 
                '&cpassword='+cpassword+ '&gender='+gender+ '&dob='+dob+ '&image='+image+ '&status='+status+
                '&submit'+submit;

                if(fname=="" || lname=="" || email==""){
                    alert("please fill the fields");
                 }else if(fname.length < 5 || fname.length > 20){
                    alert("user name must be between 5 to 20 characters");
                 }else if(password.length < 5 || password.length > 8){
                    alert("password must be between 5 to 8 characters"); 
                 }else if(!gender){
                    alert("please select your gender");
                 }else if(!dob){
                    alert("please select  your birth day");
                 }else{
                    $.ajax({
                        type:"POST",
                        url:"create-user.php",
                        data:dataString,
                        cache:false,
                        success:function(result){
                            alert(result);
                        }
                    });//ajax closed
                 }

                 return false;
            });
        });
    </script>
                <div id="content" class="col-lg-10 col-sm-10">
                        <!-- content starts -->
                <div>
                <ul class="breadcrumb">
                    <li>
                        <a href="#">Home</a>
                    </li>
                        <li>
                            <a href="#">Forms</a>
                        </li>
                    </ul>
                </div>
        <div class="box-content">
                <div id="userRegis">
                    <div class="form-group">
                            <label for="exampleInputEmail1">First Name</label>
                            <input class="form-control" id="fname" placeholder="Enter First Name" type="text" name="fname">
                        </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1">Last Name</label>
                                <input class="form-control" id="lname" placeholder="Enter Last Name" type="text">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1">Email</label>
                                <input class="form-control" id="email" placeholder="Enter Email" type="text">
                            </div>

                            <div class="form-group">
                                <label for="exampleInputEmail1">Password</label>
                                <input class="form-control" id="Password" placeholder="Enter Password" type="password">
                            </div>

            <div class="form-group">
                    <label for="exampleInputEmail1">confirm Password</label>
                    <input class="form-control" id="cPassword" placeholder="Enter confirm Password" type="password" name="cpassword">
                </div>  

            <div class="form-group">        
                    <label for="exampleInputEmail1">Gender</label>
             <div class="radio">
                    <label>
                         <input type="radio" name="gender" id="gender" value="MALE">Male
                    </label>
                         <label>
                            <input type="radio" name="gender" id="gender" value="FEMALE">Female
                        </label>
                    </div>
                </div>
                <div class="form-group">
                    <label for="exampleInputEmail1">date of birth</label>
                    <input class="form-control" id="dob" placeholder="Enter Password" type="date" name="dob">
                </div>   

                <div class="form-group">
                        <label for="exampleInputEmail1">image</label>
                        <input class="form-control" id="image" placeholder="Enter Password" type="file" name="image">
                    </div>              

                    <div class="form-group">
                        <div class="control-group">
                    <label class="control-label" for="selectError">Status</label>
                    <div class="controls">
                        <select id="status" data-rel="chosen"  name="status">
                            <option value="0">SELECT</option>
                            <option value="1">ACTIVE</option>
                            <option value="2">PENDING</option>

                        </select>
                    </div>
                </div>
             <br>
            <input type="submit" name="submit" id="submit" value="create user" class="btn btn-default">
        </div>
    </div>
</div>  
</div>
<script type="text/javascript">

        $(document).ready(function(){
            $("#submit").click(function(){

                var fname  = $("#fname").val();
                var lname  = $("#lname").val();
                var email   = $("#email").val();
                var password = $("#Password").val();
                var cpassword = $("#cpassword").val();
                var gender = $("input[name=gender]:checked").val();
                var dob    = $("#dob").val();
                var image  = $("#image").val();
                var status  = $("#status").val();
                var submit  = $("#submit").val();

             var dataString='fname='+fname+'&lname='+lname+'&email='+email+ '&password='+password+ 
                '&cpassword='+cpassword+ '&gender='+gender+ '&dob='+dob+ '&image='+image+ '&status='+status+
                '&submit'+submit;

                if(fname=="" || lname=="" || email==""){
                    alert("please fill the fields");
                 }else if(fname.length < 5 || fname.length > 20){
                    alert("user name must be between 5 to 20 characters");
                 }else if(password.length < 5 || password.length > 8){
                    alert("password must be between 5 to 8 characters"); 
                 }else if(!gender){
                    alert("please select your gender");
                 }else if(!dob){
                    alert("please select  your birth day");
                 }else{
                    $.ajax({
                        type:"POST",
                        url:"create-user.php",
                        data:dataString,
                        cache:false,
                        success:function(result){
                            alert(result);
                        }
                    });//ajax closed
                 }

                 return false;
            });
        });
    </script>
$(document).ready(function(){ $("#submit").click(function(){ var fname = $("#fname").val(); var lname = $("#lname").val(); var email = $("#email").val(); var password = $("#Password").val(); var cpassword = $("#cpassword").val(); var gender = $("input[name=gender]:checked").val(); var dob = $("#dob").val(); var image = $("#image").val(); var status = $("#status").val(); var submit = $("#submit").val(); var dataString='fname='+fname+'&lname='+lname+'&email='+email+ '&password='+password+ '&cpassword='+cpassword+ '&gender='+gender+ '&dob='+dob+ '&image='+image+ '&status='+status+ '&submit'+submit; if(fname=="" || lname=="" || email==""){ alert("please fill the fields"); }else if(fname.length 20){ alert("user name must be between 5 to 20 characters"); }else if(password.length 8){ alert("password must be between 5 to 8 characters"); }else if(!gender){ alert("please select your gender"); }else if(!dob){ alert("please select your birth day"); }else{ $.ajax({ type:"POST", url:"create-user.php", data:dataString, cache:false, success:function(result){ alert(result); } });//ajax closed } return false; }); });

you should set the validation to the submit button, and then at the bottom of the validation script, call the ajax script.


Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.
Connect Social With PHPAns
Top