Ajax表单验证后传递数据

时间:2016-04-12 15:12:04

标签: php ajax forms

我有一个表单可以验证数据,例如username password email和ajax。在验证数据之后,如何通过ajax将数据传递给php文件以在数据库中插入数据?

我只想插入数据库de值,例如email,然后我解决与加密相关的问题。

表单按钮

<input onclick="checkForm()" type='button' class="btn btn-info btn-block" value='Inserir' name="submit1">

的script.js

function checkForm() {
// Fetching values from all input fields and storing them in variables.
var name = document.getElementById("username1").value;
var password = document.getElementById("password1").value;
var email = document.getElementById("email1").value;
var website = document.getElementById("descricao1").value;
//Check input Fields Should not be blanks.
if (name == '' || password == '' || email == '' || website == '') {
alert("Por favor, preencha todos os campos");
} else {
//Notifying error fields
var username1 = document.getElementById("username");
var password1 = document.getElementById("password");
var email1 = document.getElementById("email");
var descricao1 = document.getElementById("website");
//Check All Values/Informations Filled by User are Valid Or Not.If All   Fields Are invalid Then Generate alert.
if (username1.innerHTML == 'Mais de 4 letras' || password1.innerHTML ==   'Password é pequena de mais' || email1.innerHTML == 'Email inválido' ||   descricao1.innerHTML == 'Descricao inválida') {
alert("Preencha com informação válida.");
} else {
//Submit Form When All values are valid.
//document.getElementById("myForm").submit();
sendData('regista.php', 'POST','email='+email);
}
}
}



function sendData(url, metodo, dados){
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
  alert("Enviado!");
  location.href = location.href;
 }
};
 xhttp.open(metodo, url, true);
 xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xhttp.send(dados);
}



// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validando..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;

} else {
document.getElementById(field).innerHTML = "Error Occurred. <a     href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}

0 个答案:

没有答案