dimanche 19 avril 2015

Making a simple form validator with AJAX and JSON but without jQuery

1.html : My goal is to make a simple form with name, password and password confirmation with AJAX and JSON but absolutely without jQuery.


2.javascript: make a XMLHttpRequest() with POST


3.JSON : make a php file for JSON.parse()


I want to check the availability of login and the equality of password


HTML:



<form>
<div>
<label>Login</label>
<input placeholder="Login" type="text" name="login" id="login"/>
</div>
<div>
<label>Password</label>
<input placeholder="password" type="password" name="password1" id="password1"/>
</div>
<div>
<label>Confirm Password</label>
<input placeholder="password" type="password" name="password2" id="password2"/>
</div>
<div>
<button type="submit" name="submit" id="submit">Send</button>
</div>


<div id="response"> <h1>Response</h1> </div>


JAVASCRIPT:



(function () {
var bouton = document.getElementById('submit');
var reponse = document.getElementById('reponse');

bouton.addEventListener('click', ajax, false);

function ajax() {
var xhr = new XMLHttpRequest();
var $$$ = document.getElementById('$$$').value;
var url = 'file.php?$$$=' + $$$;

xhr.open(
'POST',
url
);

xhr.send(null);

xhr.onreadystatechange = function () {


switch (xhr.readyState) {
case xhr.DONE:
if (xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
reponse.innerHTML += '<p>' + json + '</p>';

} else {
console.log('STATUS (' + xhr.status + ') : ' + xhr.statusText);
}

break;

default:
console.log('DEFAULT CASE');

break;
}
};
}
})();


PHP File:


I don't know ... with JSON




Thank you for your great help !


Aucun commentaire:

Enregistrer un commentaire