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
}
var pseudo = form.elements["pseudo"].value;;