views:

639

answers:

3

Here's what I'm trying to do.

  • When the 'Submit' form is clicked on my form, a javascript function will loop through all the fields of the form.

  • For each field a function will be called which would return true/false to indicate if it was filled in correctly or not.

  • If a false is returned, it shows an error message next to that field.

  • If all fields are correct, it submits the form. If not, it doesn't submit.

Here's the tricky part. While most of the validation is being done via javascript, the username and email need to be validated via ajax to see if the username/email is already in use or not.

The structure i'm currently using for this ajax function is something similar to this:

function validateSomething()
{
  var valid;
  $.post("something.php", {x:y},
  function(data)
  {
     if (isSomething(data))
       valid=true; 
       //Here referring to the valid variable 
       //set outside this function, in the
       // parent function
     else
       valid=false; 
  });
  return valid/
}

But that currently doesn't work.

What can I do to make it work, i.e can I stop the validateSomething() function from returning a value until its set to true/false by the inner function?

Would something like this work:

function validateSomething()
{
  var valid="unset";
  $.post("something.php", {x:y},
  function(data)
  {
     if (isSomething(data))
       valid=true; 
       //Here referring to the valid variable 
       //set outside this function, in the
       // parent function
     else
       valid=false; 
  });
  //Loop without returning until valid is set to true or false
  while (valid=='unset')
  {
     //Do nothing?
  }
  return valid/
}
+3  A: 

You can force the ajax-call to wait with async: false.

Like this using jquery:

function validateSomething() {
    var valid;
    $.ajax({
        url: "something.php",
        data: {x: y},
        type: "GET",
        async: false, // this makes the ajax-call blocking
        dataType: 'json',
        success: function (response) {
            valid= response.valid;
        }
     });
     return valid;
}

However, the big win when using AJAX is that it is asynchronous. This synchronous call might lock up the browser while it is waiting for the server.

Magnar
Ah, didin't know of that setting. Will the .ajax function make a GET or POST post?
Click Upvote
You can specify that using type. Updating answer to clarify.
Magnar
+1  A: 

You probably don't want to. (Or more appropriately, "Go for it, but be careful when doing so.")

Validating via AJAX is hip and slick and awesome. But it is -not- a substitute for validating server-side. And AJAx validation is -not- server-side validation. I can take the return of your function that says false and flip it to true and submit the form happily, even though you checked to make sure the username wasn't taken 'on the server'. Javascript runs on the client and can't be trusted.

Any validation you do via an AJAX call must be re-done on the server when you actually submit the form.

If you do that, then yea, AJAX validation is, again, hip and slick and awesome. So go for it. To submit a form using javascript (e.g. in the AJAX call-back handler function) you would say:

 if(formwasValid)
 {
      document.getElementById('idOfForm').submit();

      $('#idOfForm').submit(); //jQuery
 }
 else
 {
      alert('Invalid text');
 }
Tom Ritter
Yes. Seems pretty nonsensical to first validate using XHR (so, server side), later revalidate (server side). Server does the same twice. Why not run all in one XHR (validate, process), XHR return true/false, everybody happy.
KooiInc
@Renzo: depends on whether you want your form to work without JS or not - I normally want the former, that's why I stopped doing extensive validation in JS to avoid having to duplicate code...
Christoph
+1  A: 

I stopped doing extensive form validation on the client side as the code has to be duplicated on the server side anyway.

On the client-side, I just do some basic syntax checking of fields via regular expressions. These checks will be immediately triggered when the user starts typing, but they just give a visual notice as to when something went wrong (red border, different background color, a red 'X' next to the field...).

I don't prevent the user from submitting even invalid forms: Then, the server-side code with it's more detailed checks gets to work, which can easily restructure the form to separate valid from invalid fields and generate in-depth explanations as to why a check failed.

Christoph