instant search from database using ajax

I'm trying to code an instant search from database using jsp servlet, jquery(keyUp event) and ajax.

The search is working but when I delete the characters and the search input is empty the ajax code return all the data from database.

Frontend

$(document).ready(function(){
 
    $("#name").keyup(function(){
   
        $.ajax({
            url: 'search',      
            dataType: 'html',
            type: 'get',
            data: 'nm='+$("#name").val(),
            success: function (result) {
                $("#div").html(result); 
            },
            error: function (result) { 
                $("#div").html("Error.") ;}
        });  
    }); 

Backend

PrintWriter out = response.getWriter();
ResultSet  R=null;
String req="select * from client_alpha where 1=1";
           
if(request.getParameter("cin")!=null){
    req+= " and cin like upper('" + request.getParameter("cin") + "%')";
}
      
R=Myconnection.getcon().createStatement().executeQuery(req);

if (R.next() == false) {
    out.print("empty");
} else {
    out.print("<table>");
    do {
        out.print("<tr><td>" + R.getObject(1) + "</td><td>" + R.getObject(2) + "</td><td>" + R.getObject(3) + "</td><td>" + R.getObject(4) + "</td></tr>");
    } while (R.next());
    out.print("</table>");
}

Upvotes: 0

Views: 598

Answers (1)

Giorgos Yiakoumettis
Giorgos Yiakoumettis

Reputation: 97

If this input exposes all database entries, it means that your GET request on search?nm= returns all the data.

First things first, You need to fix this on your Backend.

Meanwhile if you need to avoid this you can add a FrontEND condition like this:

$("#name").keyup(function(){

   if ($(this).val() == '') return;
   
   console.log(`Showing Search Results for ${$(this).val()}`);
  
   $.ajax({
    url: 'search',      
    dataType: 'html',
    type: 'get',
    data: 'nm='+$("#name").val(),
    success: function (result) {
      $("#div").html(result); 
    },

    error: function (result) { 
        $("#div").html("Error.");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='name' value='test'>

Upvotes: 1

Related Questions