niel
niel

Reputation: 41

Form validation with ajax called from onsubmit

I'm trying to validate a registration form with ajax based on checking if the users IP adress already exists in my database or not.

The actual problem relies on automaticly submitting the form, independet whether my if statements is true nor false in the success handler of the ajax call. I'm aware that the ajax call is asynchronous executed and that probably the form is exexcuted before the if statement, but I have no clue how to solve that.

<form id="form" action="/chat/register" method="post" class="form-horizontal" role="form" onSubmit="return do_validation(this);">

ajax call:

function do_validation() {
    var data = {
        "action": "check",
        "username": username,
        "password": password,
        "confirm_password": confirm_password,
        "email": email
    };
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "uservisit.php", //Relative or absolute path to response.php file
        data: data,
        success: function(data) {
            if (data["ip_address"] === 0) {
                return true;
            }else{
                alert(data["ip_address"] + "\n"  + data["username"] + "\n" + data["password"] + "\n" + data["confirm_password"] + "\n" + data[$
                return false;
            }
        }
    }); return false;
}

data["ip_address"] serves the right information, if i have the ip stored in the database i get 1 alerted, if not 0.

Upvotes: 1

Views: 166

Answers (1)

niel
niel

Reputation: 41

I got a working solution, but it might not be the nicest

var retValue = false;
var data = {
  "action": "check",
  "username": username,
  "password": password,
  "confirm_password": confirm_password,
  "email": email
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
  global: false,
  type: "POST",
  dataType: "json",
  url: "uservisit.php", //Relative or absolute path to response.php file
  data: data,
  async: false,
  success: function(data) {
    if (data["ip_address"] === 0) { 
      retValue = true;
    }else{  
      alert(data["ip_address"] + "\n"  + data["username"] + "\n" + data["password"] + "\n" + data["confirm_password"] + "\n" + data["email"] + "\n" + data["visitlasttime"]);
      retValue = false;
   } console.log(retValue);
  }
 });
 }// End else
console.log(retValue);
return retValue;

Upvotes: 1

Related Questions