I'd like to do a form validation in real time.
For example, I have a input name="TituloFilme" type="text"
, I in my database I have the following ID | TituloFilme
columns.
When I am registering a new movie title in the database, I would like a script to associate the text in the input with the records in the database. Example:
If I have the movie Transformers 1 registered and write in the input "Transformers 1", I want to see a news item below the input "This movie is already registered", but if I write "Transformers 2" not yet registered ".
I would like this validation to be in real time, like, I just wrote the title and I moved to another field of the form, and when I move to another field I would like the query to be started and check if the title is already registered or not.
I have this the following example:
INDEX.PHP
<script src="../../Scripts/jquery.js"></script>
<script language="javascript" src="ajax.js"></script>
<script language="javascript">
function verificaDuplicidade(valor) {
url = "pesquisaUsuario.php?nome=" + valor; // arquivo que pesquisa se o usuario existe
div = "pesquisaUsuario"; // div com o id "pesquisaUsuario". você pode colocar qualquer nome
ajax(url, div);
}
</script>
<div id="pesquisaUsuario"></div>
<br>
<input type=text name=nome id=nome>
<input type=button name=pesquisa onClick="verificaDuplicidade(nome.value)">
AJAX.JS
function ajax(url, div) {
req = null;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
}
}
}
function processReqChange() {
if (req.readyState == 4) {
if (req.status ==200) {
document.getElementById(div).innerHTML = req.responseText;
} else{
alert("Houve um problema ao obter os dados:n" + req.statusText);
}
}
}
and the page that does the query searchUser.php
<?php
$pdo = new PDO("mysql:host=localhost;dbname=brasiltudoliberado", "root", "");
if (!$pdo) {
die('Erro ao criar a conexão');
}
if ($_GET["nome"] != "") {
$consulta = $pdo->prepare("SELECT * FROM posts WHERE TITULO = '".$_GET["nome"]."'");
$count = count($consulta);
if ($count == 1) {
echo "Já existe um Titulo igual ao pesquisado";
}
else {
echo "Não existe";
}
}
?>
"Apparently" this template works, but it always returns that there is an equal title to the one searched, which is not true.
Oh, this template also does not validate instantly, you have to click a button.