admin管理员组

文章数量:1323732

I am having a problem with this code, it's about a search box that uses ajax to make auto suggestions for the user, I am testing the code but it seems to be not working, any suggestions?

The HTML code :-

<input class="autosuggest" name="autosuggest" type="text"></input>

and the JavaScript code:-

    $(document).ready(function(){
    $('.autosuggest').keyup(function(){
        var search_term = $(this).attr('value');
        $.post('search.php', {search_term:search_term}, function(data){
            alert(data);
        });
    });
 });

Now the PHP page:-

    <?php
require_once "database/db.php";

if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false){
    echo"something";
    }
}

?>

Now this code is supposed to give me an alert box with the value "something", isn't it? It is just giving me an empty alert box and I don't know why!

Any suggestions?

I am having a problem with this code, it's about a search box that uses ajax to make auto suggestions for the user, I am testing the code but it seems to be not working, any suggestions?

The HTML code :-

<input class="autosuggest" name="autosuggest" type="text"></input>

and the JavaScript code:-

    $(document).ready(function(){
    $('.autosuggest').keyup(function(){
        var search_term = $(this).attr('value');
        $.post('search.php', {search_term:search_term}, function(data){
            alert(data);
        });
    });
 });

Now the PHP page:-

    <?php
require_once "database/db.php";

if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false){
    echo"something";
    }
}

?>

Now this code is supposed to give me an alert box with the value "something", isn't it? It is just giving me an empty alert box and I don't know why!

Any suggestions?

Share Improve this question edited Jul 6, 2016 at 4:25 Des Horsley 1,88821 silver badges43 bronze badges asked Sep 28, 2013 at 17:33 Mohammad99Mohammad99 472 gold badges2 silver badges11 bronze badges 3
  • Look at your request in debug tools (firebug or chrome development tolls). Does your server script return "something" ? Then, in your javascript code use console.log(data) and see what value does it have. – Victor Commented Sep 28, 2013 at 17:35
  • Indeed, I used console.log(search_term) and found that it's undefined. User $(...).val() to get your input value and don't forget to debug – Victor Commented Sep 28, 2013 at 17:45
  • thanks victor, i am trying now :) – Mohammad99 Commented Sep 28, 2013 at 17:50
Add a ment  | 

3 Answers 3

Reset to default 4

First of all, if you're only searching from the database, and not modifying the database in any way, you should use GET instead :) also, some changes:

  1. Use $(this).val() instead.
  2. Specify dataType as JSON. As $.get() tries to guess intelligently the dataType, it might get it wrong sometimes... especially when you are echoing plain text. So try to use JSON instead - and it will pay back later, when you are returning search results (in arrays) from your DB when you actually get around to do it.
  3. In your PHP, echo your result in JSON format using the PHP function json_encode(). See explanation above.

$(document).ready(function(){
    $('.autosuggest').keyup(function(){
        var search_term = $(this).val();
        $.get(
            'search.php',
            {
                search_term: search_term
            },
            function(data) {
                alert(data);
            },
            'json'
        });
    });
});

If you are using GET, remember to update your PHP script, too:

<?php
    require_once("database/db.php");
    if(isset($_GET['search_term']) && !empty($_GET['search_term'])){
        echo json_encode("something");
    }
}
?>

Other notes for optimization:

Throttling keyup(). I usually avoid listening to the keyup event directly, because your users may type very quickly resulting in a deluge of data sent back and forth. Instead, try throttling it with this plugin, and it's rather easy to implement:

$('.autosuggest').keyup($.throttle(250 ,function(){  // Unobstructive throttling

    // Your code here

}));  // Remember to close the parenthesis for the $.throttle() method

Use 'search' as input type. For better usability, use <input type="search" ... /> for your search field. Plus, for older or inpatible browsers that don't recognize the type, the field will simply revert back to <input type="text" ... />

Serialize form data. I rely on serialization to streamline the process, and keep the AJAX function clean from clutter (otherwise you'll have to enumerate all the fields you want to submit). This can be done easily by using $('form').serialize() (see documentation) instead of {search_term: search_term}.

I believe it has to do with your search_term variable name being the same as the name of the array key, because strings can be used as keys too. Thus, js is converting the key to a string that contains the value of .autosuggest. Try changing the variable name to the_search_term. Example:

    $(document).ready(function(){
    $('.autosuggest').keyup(function(){
        var the_search_term = $(this).attr('value');
        $.post('search.php', {search_term:the_search_term}, function(data){
            alert(data);
        });
    });
    });

You can use simple tools for auto suggestion:

  • select2
  • typeahead

本文标签: javascriptAuto Suggestion search box with php and jqueryStack Overflow