pokemon king
pokemon king

Reputation: 33

JQuery instant search: how to make a second post request. and how to make a use enter key to search

I created an instant search similar to google search using JQuery.

Q1. The post to search.php using search function searchq() then print out the returned result works fine, but the create_object.php can't get the variable txt (which has already been post successfully to search.php), any ideas on how to fix it? Q2 I want to create a function that allow the user to be directed to the first search result(which is anchored with an url) when the enter is pressed, any idea how to achieve this? I tried something but it then quickly evolves into a messy nightmare.

Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own in search.php to test it. The mysql is set with a table is called "objects", and it has one column named "name".

Thanks in advance!

 <html>
    <!-- google API reference -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <!-- my own script for search function -->

    <center>
    <form method="POST">
        <input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
        <input type="submit" value=">>">
        <div id="output">
        </div>
    </form>
    </center>   

      <!-- instant search function -->
 <script type="text/javascript">

function searchq(){
        // get the value
            var txt = $("input").val();
            // post the value
            if(txt){
                $.post("search.php", {searchVal: txt}, function(result){
                    $("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
                });
            }
            else{
                $("#search_output").html("");
            }


        };
function createq(){
    // allert for test purpose
    alert("hi");
    $.post( "create_object.php",{createVal:txt} );

}

</script>
    </html>

PHP file (search.php)

 <?php
if(isset($_POST["searchVal"])){
    //get the search
    $search=$_POST["searchVal"];
    //sort the search
    $search=preg_replace("#[^0-9a-z]#i","",$search);
    //query the search
    echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
    $query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
    $count=mysqli_num_rows($query);
    //sort the result
    if($count==0){
        $output="there was no search result";
    }
    else{
        while($row=mysqli_fetch_assoc($query)){

            $object_name=$row["name"];

            $output.="<div><a href='##'".$object_name."</a></div>";
        }
    }
    echo $output;
}
?>

php file (create_object.php)

 <?php
    if(isset($_POST["createVal"])){
        $name=$_POST["createVal"];
        var_dump($name);

    }

?>

Upvotes: 0

Views: 1228

Answers (2)

Joaqu&#237;n O
Joaqu&#237;n O

Reputation: 1451

I just made a simple change in your HTML. I removed the onkeyup attr, and added an id in order to have simpler jQuery selectors

<form method="POST">
    <input type="text" name="search" id="search" style="width:400px " placeholder="Search box">
    <input type="submit" value=">>">
    <div id="output">
    </div>
</form>

<script>
    $(document).ready(function() {

        var request;

        $("#search").on("keyup", function(e) {

            if(e.which === 13) {
                // Q2 -> Enter pressed
                var firstResult = $("#output").find("a").first();
                if(firstResult.length === 1) { // Just checking there is a result
                    window.location = firstResult.attr("href");
                }
                return false; // This prevents the form to submit
            } else {
                // Any other key
                searchq();
            }

        });

    });
</script>

Update

The reason of why you can't access the txt var from the createq function is because it's local to the searchq function, what means that outside the searchq function it doesn't exist at all.

Easiest solution is doing something like this:

var txt;
function searchq() {
    // Some code here
    // Use txt, not var txt
}
function createq() {
    // Some code here
    // Use txt, not var txt
}

New update

In searchq() you use

$("#search_output")

but it should be

$("#output")

You are also printing malformed HTML code in your search.php. It should be like this

$output.="<div><a href='##'>".$object_name."</a></div>";
// Note the missing > in the <a> tag

Upvotes: 1

n4m31ess_c0d3r
n4m31ess_c0d3r

Reputation: 3148

I am not so much familiar with PHP, so couldn't test the actual scenario. But as far as the javascript code, do check the following at your end:

Q1: You might have misspelled the function name 'createq' as 'creatq'

    ... <div id=\"create\" onclick=\"creatq() ...
    ..
    ..
    function createq(){
    ..
    }

Q2 There is a keycode assigned for each key on the keyboard. For enter key, its value is 13. You can get it by use of event.which in any event handler function.
In this case, it can be get on keyup or keypress of the input field, something like below should do:

$(document).on('keyup keypress', 'input[name=search]', function(evt) {
    if (evt.which === 13) {
       // find the first search result in DOM and trigger a click event 
       // $("#search_output").find('a').first().trigger('click');


      // OR
      // find the url of the 1st link and use document.location to redirect 
      var redirectUrl = $('#search_output').find('a').first().attr('href');
      document.location = redirectUrl;
    }
}); 

Upvotes: 0

Related Questions