1

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! :)

8
  • You should tell us how it doesn't work. You'll get better responses if you give us a starting point. Commented Dec 2, 2012 at 16:02
  • you are in dangerous swithcwation where bad guy will rune you life... why because of your code is vulnerable to sql injuction Commented Dec 2, 2012 at 16:03
  • Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial. Commented Dec 2, 2012 at 16:04
  • Lee-> Sry. It dosen't show up search results when i type something that is in the database. Nullpointer-> It's a very basic code, and later i will customize it to prevent sql injection, but thanks for the notice :) Commented Dec 2, 2012 at 16:06
  • I know about PDo, this is just a quick typed code, like i said i will safe it later :) Commented Dec 2, 2012 at 16:07

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);
        }
    }

1 Comment

For Post method you don't need to cache: false
-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.