Validation of input with "real time" query to the database, to check whether the information is already registered or not

Asked

Viewed 7,205 times

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.

  • There’s the prepare, but where is the execute?

1 answer

4


Apparently, it looks pretty simple. I’ve been researching some ways to do this, and I’ve found a very good example that might help. Here you basically watch as you type, and wait a time of 0.4s from the moment you stop writing. If you decide to use the example below, you should adapt it in some way to slower connections.

jQuery

var input = $('input'),
saida = $('.saida');

var DURACAO_DIGITACAO = 400,
    digitando = false,
    tempoUltimaDigitacao;

input.on('input', function () {
    atualiza();
});

function atualiza () {

    if(!digitando) {
       digitando = true;
       saida.html('procurando...');
    }

    tempoUltimaDigitacao = (new Date()).getTime();

    setTimeout(function () {

       var digitacaoTempo = (new Date()).getTime();
       var diferencaTempo = digitacaoTempo - tempoUltimaDigitacao;

       if(diferencaTempo >= DURACAO_DIGITACAO && digitando) {
           digitando = false;
           saida.html('exibe resultado...');
           //aqui você pode chamar a função ajax
       }

   }, DURACAO_DIGITACAO);

}

Demo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.