Search code examples
javascriptphpjqueryajaxbootstrap-popover

AJAX request to fill a popover working only once to a php file


I have made a simple search bar in which on every .keyup() event,an asynchronous request goes to a php file which then fills the data in the bootstrap popover.

The problem is that in the popover,the data is filled only once,i.e.,when I type the first character,after that the same data is shown even after multiple .keyup() events.

Here is the code:

HTML:

<input type="text" data-placement="bottom" id="search" name="search1" class="search-box" placeholder="Search..." title="Results"/>

AJAX:

$("#search").keyup(function(){
        console.log('erer');
        //var searchString = $("#search").val();
        var data = $("#search").val();
         console.log(data);
          var e=$(this);
        //if(searchString) {
            $.ajax({
                type: "POST",
                url: "do_search.php",
                data: {search:data},
               success: function(data, status, jqXHR){
                    console.log('html->'+data+'status->'+status+'jqXHR->'+jqXHR);
                    e.popover({
                    html: true,
                    content: data,
                    }).popover('show');         
              },
               error: function() {
                    alert('Error occured');
                }
            });    
        //}
    });``

PHP:

  $word = $_POST['search'];
    //echo $word;
    //$word=htmlentities($word)
    $sql = "SELECT FName FROM user WHERE FName LIKE '%$word%' ";
    //echo $sql;
    // get results
    //$sql = 'SELECT * FROM Profiles';
     $end_result = '';
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
         #$end_result.='<li>'.$row["FName"].'</li>';
        #$_SESSION['fnamer'] = $row['Fname'];
         #$end_result.='<li>'.'<a href =view_search.php>'.$row["Fname"].'</a>'.'</li>';
        echo '<a href =view_search.php>'.$row["FName"].'</a>';
    }
        #echo $end_result;
}

Even though in the success parameter of the $.ajax,the data is being printed fine,i.e.,it changes as I enter different alphabets,but the popover content does not change.

Please provide some suggestions to resolve this problem.


Solution

  • The popover is already shown. This is not the correct way of changing the popover content dynamically.

    Your code: https://jsfiddle.net/gsffhLbn/

    Instead, address the content of the popover directly:

    var popover = e.attr('data-content',data);
    popover.setContent();
    

    Working solution

    Fiddle: https://jsfiddle.net/gsffhLbn/1/