2
Sorry if the question is silly, but I don’t know much about ajax and I’m trying to make a basic form to test the validation using ajax and php (if possible). Good reading on the internet and seeing some articles, so far I arrived with the code below, but it is not working. I want that when the person is typing or when sending the form he does the validation in php and if there are any errors he returns using the error ajax.
*The ini.php file is my connection to the database, I did not query because, first I would like to test the errors and then send the data to the database. And I didn’t put in any other input so I wouldn’t complicate it by solving one.
Thank you.
HTML:
<table>
<tr>
<td><input type="text" name="nome" placeholder="Nome" maxlength="20" onBlur="Validate(this.value)"></td>
<span id="error"><?php echo $error; ?></span>
</tr>
</table>
"Ajax":
function Validate(data){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('error').innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "register.php?q=" + data, true);
xmlhttp.send();
}
PHP:
$error = array(
"Nome é obrigatório.",
"Somente 20 caracteres são permitidos.",
"Somente letras e espaços são permitidas."
);
// Get the q parameter from url
$q = $_REQUEST["q"];
if($_SERVER["REQUEST_METHOD"] === "POST"){
if(empty($q)){
echo $error[0];
} else if(!preg_match("/^[a-zA-Z]*$/", $q)){
echo $error[2];
} else if(strlen($q) > 20){
echo $error[1];
}
}
?>
You can use Pure Jquery or JS ?
– Ricardo Mota
Yes, more I know validate using Jquery or JS, I would really like to validate, using Ajax, thanks
– Leonardo Silva
You will not validate using ajax, or validate on the client side (javascript), or on the server side (php, recommended)
– Miguel
Take a look at my answer here: http://answall.com/questions/142834/enviando-uma-imagem-e-outros-dados-via-jquery-para-php/142858#142858 . Then I validated the server side
– Miguel
Thanks for the tip
– Leonardo Silva
You got an idea of how to do it?
– Miguel