Question: I have one textfield type text, when I'm typing a number of a plate, if it exist, it will must show one alert, but the event keyup doesn't work.

JS

```
$('#mat').keyup(function(){
        var matric = $('#mat').val();
        $.ajax({type: "POST",
                     url: "compruebaVeh.php",
                     data: "matric="+matric,
                     success:function(data) {
                         alert(data);
                         if(data=='ok'){
                             alert('this car already exists');
                         }
                     }
        });  
    });

```

PHP

```
<?php

 $mat=$_POST['matric'];
 ini_set('display_errors',1); error_reporting(E_ALL);
 require('conecta.php');
 $cSQL="select matricula from vehiculos;";
 $stmt=$oConni->prepare($cSQL) or die($oConni->error);
 //$stmt->bind_param('s',$_POST['matric']);
 $stmt->execute();
 $stmt->bind_result($matricula);
 while ($stmt->fetch()) {
    if($matricula==$mat){
        echo 'ok';
    }
 }   
 $stmt->close();  
?>

```

Answer: 
in php code, the assignment `$_POST['matric']=$mat;` should be reversed

`$mat = $_POST['matric'];`

also your script may echo `ok` many times depending on the data in your DB, the loop should become:

```
while ($stmt->fetch()) {
    if($matricula==$mat){
        echo 'ok';
        break;
    }
 }  

```

so now you could compare in js callback with "ok".
I'm going to fix this so you don't hammer your backend like this is set up to do. A [question on SO already deals with this](https://stackoverflow.com/questions/4220126/run-javascript-function-when-user-finishes-typing-instead-of-on-key-up)

```
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 1000; //time in ms, 1 second for example

var licenceSearch = $("#mat");

//on keyup, start the countdown
licenceSearch.keyup(function () {
    clearTimeout(typingTimer);
    if (licenceSearch.val) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping() {
    alert(licenceSearch.val());

    // ajax stuff can happen here.
}

```