1

I have a form (lets say a registration form) and onsubmit, it calls a function to validate as follows:

$.ajax({
        url : "/ajax/validate.php",
        type : "POST",
        data : $(".form").serialize(),
        success : function(data) {
            data = $.parseJSON(data);
            $.each(data, function(i, item) {
                $('#' + i).addClass('errors');
            });
        }
    });

The validate.php looks something like this:

if ($_POST['email'] == '' || filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) == false) {
    $errors['email'] = 'Not a valid email';
}
if ($errors) {
    echo json_encode($errors);
} else {
    // insert to db
}

Now all of this code is specifically for the registration form. I'll have many forms on my site. My question is, do I make a new file (like validate.php) for each individual form? Such as /ajax/save_profile_data.php etc? Do I keep each form validation separate or is there a clever way to approach this? I don't know if having a validate file for each form on my site is the correct way to do it.

1

The general answer would be yes - a separate file for each individual form. If the forms are different and need to be validated a different way, then each file will only need the code for that specific form, otherwise your one file would eventually grow too large in time. Something like /ajax/validations/register.php, /ajax/validations/login.php, /ajax/validations/profile.php, etc.,.

You could get some leverage out of this by having each of the form validation files include other intermediate files that contain re-useable methods to be shared between the different validation pages.

But for most projects I'd recommend using a framework to do as much of the work for you as possible, some of which allow you to create forms with their fields and bind them to a database table through an SQL object mapper, or something else, depending on your requirements.

1
  • Thanks for the reply. I'm thinking the same thing. I thought there would have been maybe other ways but this is all I could think of. – SeanWM Mar 22 '13 at 17:02
1

If you have multiple forms submitting to the same page (file), you can use hidden fields in your form to determine which action should take place - to identify the forms by sending along a hidden data field.

For example:

<form id='reg'>
  <input type='hidden' name='act' value='registration'>
  <!-- More HTML --> 
</form>

<form id='news'>
  <input type='hidden' name='act' value='newsletter'>
  <!-- More HTML --> 
</form>

Also, add client side validation to reduce server processing. For this purpose, you can use free jQuery Validation plugin

Download and copy to your website's directory jquery.validate.js, additional-methods.js and jQuery library itself. In pages where you wish to use validation, reference all these files.

Here is how to use it

HTML

<form action="#" method="post" name="registration">
<input type="text" name="name" required minlength="2" maxlength="30"
            pattern="^[a-zA-Z\s]+$" placeholder="Name"
            title="Name is required, and must contain between 2 and 30 alpha characters" />
</form>
<form action="#" method="post" name="newsletter">
<input type="text" name="name" required minlength="2" maxlength="30"
            pattern="^[a-zA-Z\s]+$" placeholder="Name"
            title="Name is required, and must contain between 2 and 30 alpha characters" />
</form>

JS

$(function() { 
      $("form").each(function() {
            $(this).validate({
                  submitHandler: function (form) {
                        return false; //prevent actual submit (requirements?)
                  }
            });
      });
});
0

If we're talking about a simple web page, your method should be sufficient.

If we're talking about something of a webapp that is AJAX-heavy, however, it might make sense to redirect all AJAX calls to a single ajax.php. The call should contain the action indicator (e.g. {ajax-action: "validate", form-data: "..."}).

ajax.php then decides what to do based on the action indicator, processes the call and outputs the response. It might be useful, then, to create an ajax_functions.php file which would contain all the functions that might be invoked through AJAX (split it if it becomes too large).

This way, you become more flexible with AJAX calls. For example, you can:

  • attempt to authorize the user before performing the action;

  • efficiently log the AJAX calls;

  • abstract AJAX functionality in Javascript into a single function or class customized to your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.