Search code examples
livesearch

Store the user searchword in mysql


I working on a little snippet, a live search with MySQL.

Now i think it could be nice to store/save which searchword the user, did the search on.

Example:

User search on

My new book

Then i want to store that to my databse.

The problem is with my script right now, where i trig the ajax on keyup. Then it will store.

M My My N My Ne My New .... and so on..

and so on, how can i come around this and only store the hole line ..?

$(function() {
    $("#searchword").keyup(function(){
        var text = $(this).val();
        if (text != ' ') {
            $('#result').html(" ");
            $.ajax({
                type: 'post',
                url: 'livesearch.php',
                data: { 'search': text },
                success: function(dataReturn) {
                    $('#result').html(dataReturn);
                }
            });
        }
     });
});

Solution

  • I've created a storeText(txt,time) function that will take your text as first param and time to wait before sending ajax as second param. You can change the second parameter as per your need. Add your ajax call in the function below my comment and you're good to go.

    $(function() {
        $("#searchword").keyup(function(){
            var text = $(this).val();
            if (text != ' ') {
    
                //THIS IS WHERE YOU CAN MODIFY THE TIME
                storeText(text,1000);
    
                $('#result').html(" ");
                $.ajax({
                    type: 'post',
                    url: 'livesearch.php',
                    data: { 'search': text },
                    success: function(dataReturn) {
                        $('#result').html(dataReturn);
                    }
                });
            }
         });
    });
    
    var timer;
    function storeText(txt,time){
        clearTimeout(timer);
        timer = setTimeout(function(){
    
            //ADD YOUR SAVE QUERY AJAX HERE
    
        },time);
    }
    

    Here's a JSFiddle to see it in action: https://jsfiddle.net/3n2L2v6g/ Try typing anything in the text box, it waits 1000ms before executing the code where your ajax would be.