donglanying3855 2014-01-17 07:45
浏览 23

Ajax,PHP实时搜索和显示更多代码单独工作但不能一起工作

I have a Ajax PHP Show More feature like youtube and Live search scripts but I can't get them to work together. For example my live search works but then the show more feature doesn't work with it on the search results and when I use the show more then the live search doesn't work.

They don't seem to be messing with each other. Can anyone help me out? I am new to this website so I will try my best to show my code and explain it.

INDEX.PHP

<?php 
include_once("connect.php");
$sql = "SELECT COUNT(*) FROM database";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
$item_per_page = 3; 
$total_rows = mysqli_fetch_array($query);
$pages = ceil($total_rows[0]/$item_per_page);
?>    
<!DOCTYPE html>
<head>
<script type="text/javascript">
// Show More Scripted
$(document).ready(function() {
var track_click = 0; 
var total_pages = <?php echo $pages; ?>;
$('#news-table-wrap').load("showmore_search.php", {'page':track_click}, function() {track_click++;});
$(".load_more").click(function (e){ 
$(this).hide(); 
$('.animation_image').show();
if(track_click <= total_pages){
$.post(showmore_search.php',{'page': track_click}, function(data) {
$(".load_more").show();
$("#news-table-wrap").append(data);
$("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 500);
$('.animation_image').hide();
track_click++;
}).fail(function(xhr, ajaxOptions, thrownError){
    alert(thrownError);
$(".load_more").show();
$('.animation_image').hide();
});
if(track_click >= total_pages-1){
$(".load_more").attr("disabled", "disabled");
}
}
});
});
// Live Search Script
function searchNews(value) {
$.post("showmore_search.php", {newsResult:value}, function(data){ 
    $("#news-table-wrap").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="search" id="search" class="search-box" onKeyUp="searchNews(this.value)" placeholder="Search News">
<table id="news-table-wrap" class="news-table-wrap" cellpadding="0" cellspacing="0">
</table>
<div align="center">
<div class="load_more" id="load_more_button">Show More</div>
<div class="animation_image" style="display:none;"><img src="/files/ajax-loader.gif"></div>
</div>
</body>
</html>

SHOWMORE_SEARCH.php

<?php 
include_once("connect.php");
$newsResult = $_POST['newsResult'];
$item_per_page = 3; 
$page_number = $_POST["page"];
$position = ($page_number * $item_per_page);
$sql = "SELECT * FROM database WHERE headline LIKE '%$newsResult%' OR post LIKE '%$newsResult%' ORDER BY date DESC LIMIT $position, $item_per_page";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)){
    $headline = $row['headline'];
    $author = $row['author'];
    $date = $row['date'];
    $post = $row['post'];
    $name = $row['name'];
    echo "<tr class='news-preview-wrap'>";
    echo "<td><div class='news-preview-content'><div class='news-preview-headline'><a href='news_post?name=".$name."'>".$headline."</a></div>
          <div class='news-preview-date'>Written by ".$author." on ".$date."</div>
          <div class='news-preview-post'>".$post."</div></div>
          <div class='news-more'><a href='news_post?name=".$name."'>Read More</a></div></td>";
    echo "</tr>";
} else {
    echo "<div class='search-error'>No search results were found...</div>";
}   
?>
  • 写回答

1条回答 默认 最新

  • duanbipu7601 2014-01-17 21:21
    关注

    Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.

    See live demo and source code here.

    http://purpledesign.in/blog/to-create-a-live-search-like-google/

    Create a search box, may be an input field like this.

    <input type="text" id="search" autocomplete="off">
    

    Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.

    Suppose we have the html like this. We have an input field and a list to display the results.

     <div class="icon"></div>
     <input type="text" id="search" autocomplete="off">
     <ul id="results"></ul>
    

    We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.

    Here is the JQuery.

      $(document).ready(function() {  
    
            // Icon Click Focus
            $('div.icon').click(function(){
                $('input#search').focus();
            });
    
            //Listen for the event
                $("input#search").live("keyup", function(e) {
                // Set Timeout
                clearTimeout($.data(this, 'timer'));
    
                // Set Search String
                var search_string = $(this).val();
    
                // Do Search
                if (search_string == '') {
                    $("ul#results").fadeOut();
                    $('h4#results-text').fadeOut();
                }else{
                    $("ul#results").fadeIn();
                    $('h4#results-text').fadeIn();
                    $(this).data('timer', setTimeout(search, 100));
                };
            });
    
    
            // Live Search
            // On Search Submit and Get Results
            function search() {
                var query_value = $('input#search').val();
                $('b#search-string').html(query_value);
                if(query_value !== ''){
                    $.ajax({
                        type: "POST",
                        url: "search_st.php",
                        data: { query: query_value },
                        cache: false,
                        success: function(html){
                            $("ul#results").html(html);
    
                        }
                    });
                }return false;    
            }
    
    
    
        })
    
    ;
    

    In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.

    Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.

    //search.php
    
    // Credentials
    $dbhost = "localhost";
    $dbname = "live";
    $dbuser = "root";
    $dbpass = "";
    
    //  Connection
    global $tutorial_db;
    
    $tutorial_db = new mysqli();
    $tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
    $tutorial_db->set_charset("utf8");
    
    //  Check Connection
    if ($tutorial_db->connect_errno) {
        printf("Connect failed: %s
    ", $tutorial_db->connect_error);
        exit();
    }
        $html = '';
        $html .= '<li class="result">';
        $html .= '<a target="_blank" href="urlString">';
        $html .= '<h3>nameString</h3>';
        $html .= '<h4>functionString</h4>';
        $html .= '</a>';
        $html .= '</li>';
         $search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
        $search_string = $tutorial_db->real_escape_string($search_string);
    
    // Check Length More Than One Character
    if (strlen($search_string) >= 1 && $search_string !== ' ') {
        // Build Query
        $query = "SELECT *
         FROM animals
         WHERE type LIKE '%".$search_string."%'
         UNION ALL SELECT *
         FROM birf
         WHERE type LIKE '%".$search_string."%'"
         ;
        $result = $tutorial_db->query($query);
            while($results = $result->fetch_array()) {
                $result_array[] = $results;
            }
    
            // Check If We Have Results
            if (isset($result_array)) {
                foreach ($result_array as $result) {
    
                    // Format Output Strings And Hightlight Matches
                    $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
                    $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
                $display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
    
                    // Insert Name
                    $output = str_replace('nameString', $display_name, $html);
    
                    // Insert Function
                    $output = str_replace('functionString', $display_function, $output);
    
                    // Insert URL
                    $output = str_replace('urlString', $display_url, $output);
    
    
    
                    // Output
                    echo($output);
                }
            }else{
    
                // Format No Results Output
                $output = str_replace('urlString', 'javascript:void(0);', $html);
                $output = str_replace('nameString', '<b>No Results Found.</b>', $output);
                $output = str_replace('functionString', 'Sorry :(', $output);
    
                // Output
                echo($output);
            }
        }
    
    评论

报告相同问题?