1
I would 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 columns ID | TituloFilme
.
When I am registering a new movie title in the database, I would like a script to associate the text in the input to the records in the database. Example:
If I have the movie Transformers 1 registered and write in the input "Transformers 1", I want to appear a news below the input "This movie is already registered", but if I write "Transformers 2" appear an alert so "Movie not yet registered".
I would like this validation to be in real time, like, I just wrote the title and passed to another field of the form, and when passing to another field I would like the query to be started and check whether 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 search query
<?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 model works, but it always returns that there is a title equal to the researched one, which is not true.
Ah, this model also does not instantly validate, it is necessary to click a button.
Do not build your SQL request using string concatenation - this is vulnerable to SQL input attacks. Use Prepared statements.
– hugomg
There’s the
prepare
, but where is theexecute
?– Lucas