Shibbir
Shibbir

Reputation: 2041

How can I validate form using JS and after that with PHP and Ajax?

I have an HTML form which I am validating using JavaScript like below code. All the JavasCript code is in an app.js file.

App.js file

function validateForm () {

    var amount          =   document.forms["salesform"]["amount"];               
    var buyer           =   document.forms["salesform"]["buyer"];    
    var buyerRegex      =   /^[a-zA-Z0-9_ ]*$/;     
    var receipt_id      =   document.forms["salesform"]["receipt_id"];  
    var receiptIdRegex  =   /^[a-zA-Z_ ]*$/;        
    let items           = document.querySelectorAll(".items")
    var itemsRegex      =   /^[a-zA-Z_ ]*$/;
    var buyer_email     =   document.forms["salesform"]["buyer_email"];  
    var note            =   document.forms["salesform"]["note"];  
    var city            =   document.forms["salesform"]["city"];  
    var cityRegex       =   /^[a-zA-Z_ ]*$/;
    var phone           =   document.forms["salesform"]["phone"];
    var phoneRegex      =   /^[0-9]*$/;
    var entry_by        =   document.forms["salesform"]["entry_by"];
    var entryByRegex    =   /^[0-9]*$/;

    function validateEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
    }

    if (amount.value == "") { 
        alert("Please enter the amount."); 
        amount.focus(); 
        return false; 
    } else if (isNaN(amount.value)) {
        alert("Amount must be only numeric value."); 
        amount.focus(); 
        return false; 
    } else if (amount.length > 10 ) {
        alert("Amount must be less than 10 characters long."); 
        amount.focus(); 
        return false; 
    }

    // more validation.....

    return true;
}

In this file I have another jQuery Ajax code validate the form using Server. So that I have added following Ajax code blow that JS validation code:

$("#salesForm").submit(function(e) {
    e.preventDefault();
    $.ajax({
        url : '../process/add-data.php',
        type: 'POST',
        dataType: "html",
        data : $(this).serialize(),     
        beforeSend : function () {
            $(".formResult").html("Please wait...");
        }, 
        success : function ( data ) {
            $(".formResult").html( data );
        }
    });
}); 

for the HTML form

<form name="salesform" id="salesForm" onsubmit="return validateForm();" method="POST">

Now when the form is validating using JavaScript then it also vaidating the form using Ajax.

But first its should validate using JavaScript and then Ajax.

Upvotes: 0

Views: 48

Answers (2)

Fabrizio Valencia
Fabrizio Valencia

Reputation: 22195

You need to return false inside beforeSend callback, as it is described in official jQuery documentation:

beforeSend Type: Function( jqXHR jqXHR, PlainObject settings )

A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.

So, you need to do something like this:

beforeSend : function () {
    $(".formResult").html("Please wait...");
    if(!validateForm()) {
        // Here you remove your "Please wait..." message
        return false;
    }
    // Or simply return the value from validateForm():
    // return validateForm();
},

And, of course, remove the onsubmit="return validateForm();" from your form tag.

Upvotes: 1

Cray
Cray

Reputation: 2850

Remove onSubmit from the element and modify your Ajax function to return invalid form BEFORE making the call.

$("#salesForm").submit(function(e) {
    e.preventDefault();

    if(!validateForm()) return;

    $.ajax({
        url : '../process/add-data.php',
        type: 'POST',
        dataType: "html",
        data : $(this).serialize(),     
        beforeSend : function () {
            $(".formResult").html("Please wait...");
        }, 
        success : function ( data ) {
            $(".formResult").html( data );
        }
    });
}); 

Upvotes: 1

Related Questions