Validation of input with query in "real time" to the database, to verify if the information already registered or not

1

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.

    
asked by anonymous 18.11.2014 / 22:30

1 answer

4

Apparently, it sounds pretty simple. I've been researching some ways to do this, and found a very good example that can serve. Here you basically watch as you type, and wait a time of 0.4s from the time you stop writing. If you decide to use the example below, you should adapt it in some way for 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

    
20.11.2014 / 03:29