简体   繁体   中英

Validating and Submitting a form using Javascript + Ajax

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, ie 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/
}

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.

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 (eg in the AJAX call-back handler function) you would say:

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

      $('#idOfForm').submit(); //jQuery
 }
 else
 {
      alert('Invalid text');
 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM