tags:

views:

187

answers:

1

Hi there. Please forgive the awkwardness of this question, I honestly don't know how to phrase a better query...

The situation:

I have a basic contact form within an xhtml/php page that I'm in the process of upgrading. I recently added a new unrelated jquery plugin on this page, so I would like to use the jquery functionality to help with some simple form validation if possible. The validation is already being done via PHP in a separate file submitted by the contact form.

What I want to happen, is for the PHP validation message to be passed back to the main (contact form) page without a new pageload. I've seen this done by means of jquery somewhere, but I can't seem to find it again either here or via google. Can anyone help?

I'm really looking for speed and simplicity here, and at first glance, the jquery validation plugin is daunting in its size and complexity, so I'm loath to embark on that particular route...

+1  A: 

What you are looking for is known as AJAX, and there's nothing hard about it, especially with jQuery! The problem with sending the data to PHP to validate is that it would immediately nix your requirement for "speed" - the form would need to hang while Javascript makes a request to the server to see if everything is alright. For this reason, it is common practice to have validation done in both server and client side. Note I'm saying both, as you should always validate data on the server.

With this in mind, let's get started! I am going to show how to validate a form without using the validation plugin - for bigger projects, you might want to consider it, but it is easy enough without it:

<form id='myform' action='whatever.php' method='POST'>
First Name: <input type='text' name='first_name' class='required'><br>
Last Name: <input type='text' name='last_name'><br>
Email: <input type='text' name='email' class='required'><br>
Zip: <input type='text' name='zip'><br>
</form>

So as you can see we have first name and email with a class of required, so we can do this:

$(function() { // wait for the document to be loaded
    $('#myform').submit(function() {
        var valid = true; // assume everything is okay
        // loop through each required field in this form
        $('input.required', this).each(function() {
            // if the field is empty, mark valid as false
            // and add an error class
            if($.trim($(this).val()) == '') {
                valid = false;
                $(this).addClass('error_input');
            }
        });

        // additional validation for email, zip, perhaps

        return valid; // if valid is true, continue form submission
    });
});

The Validation plugin makes this all a little neater and cleaner to do, but if you just need to do a quick form there is nothing wrong with the approach above. It does suck because you have to have your validation rules in two places, but apart from executing Javascript on the server or calling the server for the data there is no alternative if you want to quickly tell your users something is wrong.

Hope this helps.

EDIT: Seems I misunderstood your question. If you want to pass the form data to a PHP script, have it validate the values, and return success or error back to the page without a load, you would do something like this:

$('#myform').submit(function() {
    // allow submit if we've validated this already
    if($(this).data('done')) return true;
    var data = $(this).serialize(); // serialize the form data
    // you could get the two variables below from the actual form (DRY)
    // with $(this).attr('action'); and $(this).attr('method'); but I am
    // not sure if that is what you want...
    var action = 'validate.php'; // what script will process this
    var method = 'POST'; // type of request to make
    $.ajax({
        type: method,
        url: action, 
        data: data,
        dataType: 'json',
        success: function(d) {
            if(d.code == 'success') {
                 // everything went alright, submit
                 $(this).data('done', true).submit();
            } else {
                 alert('something is wrong!');
            }
        }
    });
    return false; // don't submit until we hear back from server   
});

And then all your PHP script has to do is return something like this, using json_encode, to indicate whether everything is alright or not:

// verify everything...
// data will be in $_POST just like a normal request
if($everythingOK) {
    $code = 'success';
} else {
    $code = 'error';
}
print json_encode(array('code' => $code));
exit;

I haven't tested the Javascript above, but I am pretty sure it should be about right. I hope this helps. :)

Paolo Bergantino
Michael D