0

Hi guys its my first time trying out a live ajax search for my site. I am new to php so any help on this matter would be great. I was following some tutorials here and there and trying to make it work, but every time i press search no results come up at all. Any help on this matter would be great.

Code:

<?php
mysql_connect("localhost","root","") or die ("could not connect");
mysql_select_db("reg") or die ("could not find db");
if (isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {
    $search_term = mysql_real_escape_string($_POST['search_term']);
    $query = mysql_query("SELECT `ingName` FROM `ing` WHERE `ingName` LIKE '$search_term%'");
    while(($row = mysql_fetch_assoc($query)) !== false) {
    echo '<li>',$row['ingName'],'</li>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>

    <div class="container">
        <input type="text" class="searchFunction"> <input type = "submit" value ="Search">
        <div class = "dropdown">
        <ul class = "result">
        </ul>
        </div>
    </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $('.searchFunction').keyup(function() {
        var search_term = $(this) .attr('value');
        $.post('build.php', {search_term:search_term}, function(data) {
            $('.result').html(data);

            $('.result li').click(function() {
            var result_value = $(this).text();
            $('.searchFunction').attr('value', result_value);
            $('.result').html('');
    });
    });
});
});

    </script>

  </body>
</html>

Again i am so new to this, so i am just trying to build my knowledge around this area. Any help in solving this big problem out would be great

P.S i know about the sql injections :) but one step at a time for now x

Nevershow2016
  • 570
  • 6
  • 19
  • your input doesn't hold either an id or a `search_term` name attribute. check for errors via PHP http://php.net/manual/en/function.error-reporting.php and check your console. – Funk Forty Niner Feb 29 '16 at 12:54
  • the form input element should have a name – Professor Abronsius Feb 29 '16 at 12:56
  • Where is your php code? Can you edit that in your question. Also, why are you using two jquery libs? – Zeeshan Hyder Feb 29 '16 at 13:00
  • try to `console.log(data)`.. what do you get? You can also use the browsers developer tools (chrome F12) to analyse the XHR traffic which ay show you any errors that might have occurred. – DevDonkey Feb 29 '16 at 13:03
  • [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Feb 29 '16 at 13:19
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Feb 29 '16 at 13:19

2 Answers2

2

As has been pointed out - the method used so far is at risk of sql injection so before getting committed to using the now deprecated mysql suite of functions you would be wise to read up on and implement mysqli which, when you employ prepared statements will offer significant protection from malevolent sql injection attacks.

As your ajax query is being sent to the same page ( by the looks of code posted ) one important thing to do is exit from the phpafter sending the response - otherwise you end up sending the entire page ( which would also be badly formed as there would be content outside the html tags ) and I suspect this is not your desired goal.

The ajax function looks, to my untrained eye, ok but as I don't use jQuery I might well be wrong and have missed something important.

<?php
    /*
       as the rest of the page doesn't use a db connection, 
       only load the db conn if the page is requested via post
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        /* assign db connection to a variable */
        $conn=mysql_connect("localhost","root","") or die ("could not connect");

        mysql_select_db("reg") or die ("could not find db");

        /* empty() does an implied `isset` */
        if ( !empty( $_POST['search_term'] ) ) {

            $search_term = mysql_real_escape_string( $_POST['search_term'] );

            /* 
               You ought to look at using mysqli ( prepared statements )
               rather than the now deprecated `mysql_*` functions
            */
            $query = mysql_query( "SELECT `ingName` FROM `ing` WHERE `ingName` LIKE '$search_term%'", $conn );

            if( $query ){/* only send response if the query succeeds */
                while( $row = mysql_fetch_assoc( $query ) ) {
                    echo '<li>',$row['ingName'],'</li>';
                }
            }
        }

        mysql_close( $conn );
        /* make sure that the rest of the page is not sent back with the response data */
        exit();
    }
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Gotta have a title!</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript">
        $( document ).ready( function() {
            $('.searchFunction').keyup( function( event ) {
                /* I could not get this to work - I don't know what this is doing as I don't use jQuery */
                /*var search_term = $(this).attr('value');*/


                /* this however does work */
                var el=event.target || event.srcElement;
                var search_term=el.value;

                /* maybe better to search after a few letters have been added? */
                if( search_term.length < 2 )return;

                /* it appears you are posting to the same page */
                $.post( document.location.href, { search_term:search_term }, function( data ) {
                    $('.result').html( data );

                    $('.result li').click( function( event ) {
                        var result_value = $(this).text();

                        $('.searchFunction').attr('value', result_value );
                        $('.result').html('');
                    });
                });
            });
        });
    </script>
  </head>
  <body>
    <div class="container">
        <input type="text" name='search_term' class="searchFunction">
        <input type="submit" value="Search">
        <div class="dropdown">
            <ul class="result"></ul>
        </div>
    </div>
  </body>
</html>

Full, working example

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        if ( !empty( $_POST['search_term'] ) ) { 

            $dbhost =   'localhost';
            $dbuser =   'root'; 
            $dbpwd  =   'xxx'; 
            $dbname =   'xxx';

            $db =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

            /* using lower() helped account for vagueries in spelling */
            $sql='select * from `maps` where 
                    lower( `location_name` ) like lower( "%'.$_POST['search_term'].'%" );';

            $res=$db->query( $sql );
            if( $res ){
                while( $rs=$res->fetch_object() ){
                    echo "<li>".$rs->location_name."</li>";
                }
            }
        }
        exit();
    }
?>
<!doctype html>
<html lang='en'>
  <head>
    <title>Gotta have a title!</title>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
    <script type='text/javascript'>
        $( document ).ready( function() {
            $('.searchFunction').keyup( function( event ) {

                var search_term=this.value;

                /* maybe better to search after a few letters have been added? */
               if( search_term.length < 5 )return;

                /* it appears you are posting to the same page */
                $.post( document.location.href, { search_term:search_term }, function( data ) {
                    $('.result').html( data );

                    $('.result li').click( function( event ) {
                        var result_value = $(this).text();

                        $('.searchFunction').attr( 'value', result_value );
                        $('.result').html('');
                    });
                });
            });
        });
    </script>
  </head>
  <body>
    <div class='container'>
        <input type='text' name='search_term' class='searchFunction'>
        <input type='submit' value='Search'>
        <div class='dropdown'>
            <ul class='result'></ul>
        </div>
    </div>
  </body>
</html>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • C'mon Ram - you know that code only answers are ***bad*** answers. :) – Jay Blanchard Feb 29 '16 at 13:19
  • i did put in comments here and there - but truth be told - my heart really isn't in it at the moment – Professor Abronsius Feb 29 '16 at 13:26
  • Sorry to hear that Ram. – Jay Blanchard Feb 29 '16 at 13:27
  • thought i'd better add some notes - you are right of course, code only answers are bad – Professor Abronsius Feb 29 '16 at 14:01
  • Hi there thanks so much for the answer, back , however for some reason it still is not working now – Nevershow2016 Feb 29 '16 at 14:23
  • No drop down function appears now when i write in the box – Nevershow2016 Feb 29 '16 at 14:23
  • Is it because i have the javascript at the bottom of the page? althought i dont think that would make a difference – Nevershow2016 Feb 29 '16 at 14:26
  • Ah when i use the google chrome to see the developer tool it says that this line is an error " if( search_term.length < 2 )return;" uncaught TypeError: Cannot read property 'length' of undefined – Nevershow2016 Feb 29 '16 at 14:30
  • aha - ok, just delete that line ~ I only put it in so that you don't do a search on a single character. But the fact that it says of undefined suggests that `search_term` is blank. Try adding in an alert statement or similar ~ ie `alert( search_term )` before the ajax request – Professor Abronsius Feb 29 '16 at 15:32
  • Hmm i tried this, and it fixed that problem however now it shows nothing, for example i write some words but nothing appears – Nevershow2016 Feb 29 '16 at 15:55
  • Is the ajax request sent ok ( look in the console ) and how far into the php do you get if the ajax is sent ok ( put debug statements in )? I just ran this up using mysqli and a search of one of my tables and it was fine so it suggests that the problem might well be in the php. I found that the `like` operator was case-sensitive ( curiously ) in the results ~ is that a possibility for your lack of results here? – Professor Abronsius Feb 29 '16 at 16:12
  • @RamRaider I am not to sure , i have mae sure all is correct but still not working, i will keep going and see what i can do – Nevershow2016 Feb 29 '16 at 16:39
0

You can try writing your query without the quotations ie:

 $query = mysql_query("SELECT ingName FROM ing WHERE ingName   LIKE   '$search_term%'");

and you can also loosen your search by using '%$search_term%' instead of '$search_term'.

Another possible issue is the mysql_connect(). I was using that function and it did not work for me so I resolved to the mysqli_connect() function which worked for me.

Some more advise, you do not need the ==true and you can also you can use !empty($_POST['search_term']).

Once you are through learning that you can also try the PDO function which is far much better than initiating your own connection. You initiate a PDO connection like this.

$dbh1 = new PDO('mysql:dbname=dbname;host=127.0.0.1', 'username', 'dbpass');

Then you can search like this. - using the initialized connection.

 $query = "SELECT ingName from ing WHERE ingName LIKE %$search_term%";
 $stmt = $dbh1->prepare($query);
 $stmt->execute();
 $allRows = count($stmt);
 $row = $stmt->fetch(PDO::fetch_assoc);
 foreach($row as $one){
      echo "<li>".$one['ingName']."</li><br>";
 }

Cheers!