Home > front end >  Ajax LIve Search - Onclick Populate Input Value
Ajax LIve Search - Onclick Populate Input Value

Time:01-09

JQuery/Ajax Live Vehicle Search (Via Registration) With PHP Database Fetch

I'm facing a issue whereby when I click on the live search result the result is not then populated into the search input field.

I'm sure it'll be something basic but I've been looking at this for too long now and have gone fridge blind!!

Form field users search with:

<form>
  <input type="text" id="vehicle" name="vehicle" value="">
  <div id="vehicle-output"></div>
</form>

Jquery/Ajax in footer

$(document).ready(function(){
    /// Live Search ///
    $("#vehicle").keyup(function(){

        var query = $(this).val();
        if (query !="") {
            $.ajax({
                url:"includes/veh-search.php",
                type:"POST",
                cache:false,
                data:{query:query},
                success:function(data){

                    $("#vehicle-output").html(data);
                    $('#vehicle-output').css('display', 'block');

                    $("#vehicle").focusout(function(){
                        $('#vehicle-output').css('display', 'none');
                    });
                    $("#vehicle").focusin(function(){
                        $('#vehicle-output').css('display', 'block');
                    });
                }

            });
        }

        else {
            $("#vehicle-output").html("");  
            $('#vehicle-output').css('display', 'none');
        }

    });
    /// Click to enter result ///
    $("#vehicle-output a").on("click", function(){
        $("#vehicle").val($(this).html());
    });

});

PHP/MySQL For Search

include('db.php');

if(isset($_POST['query'])) {

    $retval = '';

    $retval .= '<div >';
     
    $result = $db->query("SELECT * FROM vehicles WHERE reg LIKE '%{$_POST['query']}%' LIMIT 10");
 
    if ($result->num_rows > 0) {

        while ($vehicle = $result->fetch_assoc()) {
            
            $retval .= '<a href="#" >'.$vehicle['reg'].'</a>';

        }

    }

    $retval .= '</div>';

    echo $retval;
 
}

CodePudding user response:

See my comment concerning avoiding SQL Injection attacks.

When the document becomes ready you are attempting to set event handler so that all <a> tags within the <div id="#vehicle-output"> tag will respond to a click event. But at that point there are no such <a> tags because you haven't done any live searches yet. Just because you then subsequently append some <a> tags to the <div> doesn't cause an event handler to automatically get attached retroactively.

You need to move the setting of the "click" handlers from the "document ready" handler to the "success" return. The other issue is the call $('#vehicle-output').css('display', 'none'); to hide the results from the PHP script when the input loses focus. The problem is that the <a> element becomes invisible before the click event can possibly be taken.

You can do one of two things:

  1. Get rid of the focusin and focusout events altogether
$(document).ready(function(){
    /// Live Search ///
    $("#vehicle").keyup(function(){

        var query = $(this).val();
        if (query !="") {
            $.ajax({
                url:"includes/veh-search.php",
                type:"POST",
                cache:false,
                data:{query:query},
                success:function(data){

                    $("#vehicle-output").html(data);
                    $('#vehicle-output').css('display', 'block');

                    /// Click to enter result ///
                    $("#vehicle-output a").on("click", function(){
                        $("#vehicle").val($(this).html());
                    });
                }

            });
        }

        else {
            $("#vehicle-output").html("");
            $('#vehicle-output').css('display', 'none');
        }

    });

});

  1. Set a windows timer to change the CSS display value so that you are sure that the click event occurs (just be sure that you use a large enough timer value (500 ms. should do it)
                    $("#vehicle").focusout(function(){
                        window.setTimeout(function() {
                            $('#vehicle-output').css('display', 'none');
                        }, 500);
                    });
  •  Tags:  
  • Related