Ajax'ı öğreniyorum. Bir json dosyasında (users.json) varolan seçili kullanıcının olup olmadığını kontrol etmek için ajax kullanarak bir formu doğrulamam gerekir. Var checkPseudo'nun değerini almam lazım. Aslında bu var her zaman "tanımsız" dır.Form doğrulama: Eşzamansız dönüş değeri alma
Bu, asenkron geliştirme ile klasik bir sorun olduğunu düşünüyorum.
Not: Jquery kitaplığını kullanamıyorum.
İşte İlk argüman olarak pseudo
geçmek unutuyorsunuz
<!-- 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
}
Öğe değerlerini almak için hata yapıyorsunuz, bu 'var pseudo = form.elements ["pseudo"]. value; '; – itzmukeshy7