mysql php js live search

空扰寡人 提交于 2019-12-24 07:39:16

问题


I'm currently doing a live search form based on Jquery/ajax/php, but it dosent seems to work. Can you guys se a problem in my code? :)

function getStates(value) {
  $.post("search.php",{ partialState: value }, function(data) { 
    $("#results").html(data);
  });
}

<input type="text" onkeyup="getStates(this.value)" />
<div id="results"></div>

Search.php:

$partialStates = $_POST['partialState'];
$states = mysql_query("SELECT institution_name FROM sb_institutions WHERE institution_name LIKE '%$partialStates%'");

while($stateArray = mysql_fetch_array($states)) {
    echo "<div>" . $state['institution_name'] . "</div>";
}

Thanks! :)


回答1:


Your Code looks ok.

The best way to troubleshoot ajax is to use Firefox with Firebug extension.

That way you can see :

  1. if the function is being fired
  2. if the $_POST values are good : url + parameters
  3. what the server sends as a response
  4. if you have errors in your js

    All this will be in the console tab of firebug. after installing firebug right click on the page and choose debug with firebug.




回答2:


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\n", $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);
        }
    }



回答3:


Please also see this http://crewow.com/AutoSuggest_Search_Tutorial.php Live Search Tutorial is a PHP Ajax Based Tutorial which containts following pages and Folders.



来源:https://stackoverflow.com/questions/13670979/mysql-php-js-live-search

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!