2

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"];
?>
2
  • Not much, I have searched the web for some simple validations parts with jquery but that is to difficult to start with Commented May 6, 2014 at 14:21
  • best way is to learn it by go through some examples and tutorials in internet Commented May 6, 2014 at 14:25

2 Answers 2

5

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...)

Sign up to request clarification or add additional context in comments.

6 Comments

In validation.php I can use like normally the POST method?
Yes, there should be a $_POST["name"] variable and a $_POST["password"] variable available...
Okay, but how can I return from validation.php the valid variable? And what is the difference between the part .done(function( data )){} and if(valid{ return true })
you can have validation.php just echo 'true' or 'false', so a string. I've updated my code sample.
yes, and if you use JSON as your datatype for the request, 'data' will be the actual JSON object
|
0

There is two solutions who might help you

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.