zm455
zm455

Reputation: 499

Form validation: getting asynchronous return value

I am learning ajax. I need to validate a form using ajax to check if user selected pseudo is present in a json file (users.json). I need to get the value of var checkPseudo. Actualy this var is always "undefined".

I think this is a classic problem with asynchronous development.

note: I may not use Jquery library.

Here is my code

<!-- This is my form -->

<form method="post" id="frmInscription" action="adduser.php" onsubmit="return formValidation(this)">
    Pseudo :<input name="pseudo" type="text" /><br />
    <input type="submit" name="send" value="Submit" />
</form>


<!-- javascript functions to validate the form -->

function makeRequestCheckPseudo(callback){
    if(xhr = createXhr()){ // returns an xhr object
        xhr.open("GET", "users.json", true);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status == 200){
                //I use a callback function to get the ajax responseText in the function formValidation(frm)
                callback.apply(xhr);
                return callback(); //I'm not sure if I need to return the callback function
            }                
        }
        xhr.send(null);
    };
}

function formValidation(form){
    var pseudo = form.elements["name"].value;                
    var checkPseudo = makeRequestCheckPseudo(function(){
        var jsonPseudos = JSON.parse(this.responseText); // here I get the datas from users.json by ajax response
        if(!jsonPseudos[pseudo]){ //if pseudo is present in the json object properties
            alert("pseudo is not present in users.json !");
            return true; // I want to send my form
        } else {
            alert("pseudo is present users.json !");
            return false; // I don't want to send my form          
        }
    });
    return checkPseudo; // should be "true" or "false" but I get "undefined" 
    //if checkPseudo is false the form will not be send
    //if checkPseudo is true the form will be send
}

Upvotes: 1

Views: 1728

Answers (3)

itzmukeshy7
itzmukeshy7

Reputation: 2677

Try this ;)

function formValidation(form){
  var pseudo = form.elements["pseudo"].value;                
  if(xhr = createXhr()){ // returns an xhr object
    xhr.open("GET", "users.json", true);
    xhr.onreadystatechange = function(){
      if(xhr.readyState == 4 && xhr.status == 200){
        var jsonPseudos = JSON.parse(this.responseText); // here I get the datas from users.json by ajax response
        if(!jsonPseudos[pseudo]){ //if pseudo is present in the json object properties
          alert("pseudo is not present in users.json !");
          return true; // I want to send my form
        } else {
          alert("pseudo is present users.json !");
          return false; // I don't want to send my form          
        }            
    }
    xhr.send(null);
  }
}

Try a single function and you are referencing a field in wrong way here: var pseudo = form.elements["name"].value;

Upvotes: 1

Roy
Roy

Reputation: 1967

You are forgetting to pass pseudo as the first argument. Might fix the issue.

function formValidation(form){
    var pseudo = form.elements["name"].value;                
    var checkPseudo = makeRequestCheckPseudo(pseudo, function(){
        // rest of the code
    })
}

And in case of this line:

return callback();//I'm not sure if I need to return the callback function

I guess you need to return the callback() function. Otherwise the return value will not be set to checkPseudo at the line:

var checkPseudo = makeRequestCheckPseudo(pseudo, function(){
    // rest of the code
}

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388406

Because that is how async programs work.

What you can do is to by default prevent the form submit, then if the validation is successful then manually call the form's submit method

function makeRequestCheckPseudo(pseudo, callback) {
  if (xhr = createXhr()) { // returns an xhr object
    xhr.open("GET", "users.json", true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        //I use a callback function to get the ajax responseText in the function formValidation(frm)
        callback.apply(xhr);
        callback(); //I'm not sure if I need to return the callback function
      }
    }
    xhr.send(null);
  };
}

function formValidation(form) {
  var pseudo = form.elements["name"].value;
  var checkPseudo = makeRequestCheckPseudo(function() {
    var jsonPseudos = JSON.parse(this.responseText); // here I get the datas from users.json by ajax response
    if (!jsonPseudos[pseudo]) { //if pseudo is present in the json object properties
      alert("pseudo is not present in users.json !");
      form.submit(); //if the validation is successfull then manually trigger the form submit
    } else {
      alert("pseudo is present users.json !");
    }
  });
  return false; //prevent the default action
}

Upvotes: 2

Related Questions