1

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
}
1
  • 1
    You are making mistake to get element values this should be var pseudo = form.elements["pseudo"].value;; Commented Apr 4, 2016 at 13:16

3 Answers 3

2

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
}
Sign up to request clarification or add additional context in comments.

7 Comments

Your solution works ! Thank you so much sir ! May I ask you another question ? What if I need to make a second ajax validation after the pseudo validation ? Exemple: After having checked the pseudo with ajax I would like to check if email is in email.json. Where is the best moment in my code have I to do that second ajax validation ? Inside the first ajax validation ?
form.submit(); should be replaced with the second ajax request, then inside that success handler you need to do form.submit();
Ok I understand. Thank you so much. Then It is not possible to return a value as I wished to do because this is how ajax works. Sir I can't vote for you right now because I haven't enough reputation but I promise to come back because you mad my day. Have my respect please
I can't accept it now because the stackoverflow's system tells me I need to have more "reputation" score to be able to vote . . . so all I can do is to promise you I will come back to accept your answer when my reputation will be high enough ... I will not forget you @Arun P Johny.
@zm455 it is not up voting, there is a accept tick mark
|
1

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
}

1 Comment

@Rot thank you for your suggestion. In fact I need to edit my code here because I was trying some tests by passing this "pseudo" arguments. I mean in my production code I do not use this "pseudo" argument But thank you very much !
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.