Thom
Thom

Reputation: 621

Simple Validation with PHP using AJAX and JQuery

I am new to AJAX, and I want to learn how to validate a form. Suppose, I have a form with two input fields. When I click in submit I want to check the page with a php script.
When the validation is succesfull I want to redirect to the action="submitForm.php". When one or more fields are not valid according to the validation.php I want to stay on the page and gives a error message next to the field.

What is the best way to do that?

<html>
    <head>
    </head>
    <body>
        <form action="submitForm.php" action="POST">
            <input type="text" name="username" />
            <input type="password" name="password" />
            <input type="submit" name="submit" />
        </form>
    </body>
</html>

submitForm.php:

<?php
    echo $_POST["username"];
    echo "<br />";
    echo $_POST["password"];
?>

Upvotes: 2

Views: 6825

Answers (2)

Reinder Wit
Reinder Wit

Reputation: 6615

In order to process the fields before actually submitting the form, you can catch its submit event:

<form action="submitForm.php" action="post" onsubmit="return MyValidation()">

Then, in your javascript:

function MyValidation() {
    var valid = false;

    $.ajax({
        type: "POST",
        url: "validation.php",
        async: false,
        data: { name: $('#username').val(), password : $('#password').val() }
    })
    .done(function( data ) {
        if(data == 'true') {
            valid = true;
        }
    });         

    // not valid, return false and show some hidden message
    return valid;
}

(you need to add an ID to the <input> fields in order for the jquery selectors to work...)

Upvotes: 5

Related Questions