0

A while ago i made a search function with ajax and php. You could fill in a textbox with text and it would try to find a match among all countries stored in the database. Now i am refining the code and making it PDO, but i broke something and i cant find out what.

this is my plain HTML

<head>
    <title>Ajax</title>
    <link href="style/style.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="scripts/Javascript.js"></script>
</head>

<body>
    <div id="main">
            <h1 class="title">Enter your country please</h1>

        <input type="text" id="search" autocomplete="off" onchange="">
            <h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>

        <ul id="results"></ul>
    </div>
</body>

here is my Jquery and javascript. note i have not changed anything to the HTML nor javascript so it can not by a type error.

$(document).ready(function() {
alert('asdf');

function search() {
    var query_value = $('input#search').val();
    $('b#search-string').html(query_value);

    if(query_value !== ''){
        $.ajax({
            type: "POST",
            url: "search.php",
            data: { query: query_value },
            cache: false,
            success: function(html){
                $("ul#results").html(html);
            }
        });
    }

    return false;
}

$("input#search").live("keyup", function(e) {
    clearTimeout($.data(this, 'timer'));
    var search_string = $(this).val();

    if (search_string == '') {
        $("ul#results").fadeOut();
        $('h4#results-text').fadeOut();
    }

    else {
        $("ul#results").fadeIn();
        $('h4#results-text').fadeIn();
        $(this).data('timer', setTimeout(search, 100));
        };
    });
});

And here is my Search.PHP

<?php
class SearchEngine{

    private $html;

    public function __construct($conn){

        $this->html = '<li class="result">
                            <h3>NameReplace</h3>
                            <a target="_blank" href="ULRReplace"></a>
                        </li>';

        if (isset($_POST["query"])) {
            $search_string = mysql_real_escape_string($search_string);
        }

        else{
            $search_string = 'b';
        }

        if (strlen($search_string) >= 1 && $search_string !== ' ') {

            $query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
            $result = $conn->prepare($query);
            $result->execute();
            $result_array = $result->fetchAll();

                foreach ($result_array as $result) {
                    $display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
                    $display_url = 'sadf';

                    $output = str_replace('NameReplace', $display_name, $this->html);
                    $output = str_replace('ULRReplace', $display_url, $output);
                    echo($output);
                }
        }
    }

    }
?>

The problems:

  1. the Post query is never created, for this i made a isset so for now when there is no Post Query created. It will create a Post Query with value "B".

  2. I think the page never gets updated, but i cant be 100% sure since the post never gets created so there is never a update to the query. And for some reason the results are not placed in there correct spot.

Any help will be much appreciated. Please be gentle i am new to Ajax and i rather want to understand than have the solution. Thank you

4
  • 1
    if you var_dump($_POST); - is anything displayed? What happens if you try to manually navigate to the PHP Page that updated the SQL? Commented Jun 29, 2014 at 10:48
  • I can not var_Dump the post because it never gets created. I tested the javascript.js and the functions within are called but aren't doing what they are supposed to do. and what do you mean with manual navigate to PHP page? Commented Jun 29, 2014 at 11:02
  • @KrijnvanderBurg you still need help with this question? Commented Jul 7, 2014 at 22:03
  • I asked this question 10 minutes again and it was solved. but now i have another problem. that it returns the HTML twice. But your answer has a few other flaws mentioning my code so i will look into it. Commented Jul 7, 2014 at 22:06

1 Answer 1

1

Are you really posting your search string to a PHP class?

That's not how it works, you need to create an instance of that class and use it.

Create a separate php file for that class, and included it in search.php

You can have a simple class looking like the following:

search_engine.php

<?php
class SearchEngine{

    private $conn;

    function __construct($conn){
        $this->conn = $conn;
    }

    function get_search_results($search_string){
        $query = 'SELECT * FROM country WHERE name LIKE :search';
        $result = $this->conn->prepare($query);
        $result->execute(array(':search'=>'%'.$search_string.'%'));
        $result_array = $result->fetchAll();

        return $result_array;   
    }
}
?>

search.php

if (isset($_POST["query"])) {
    $search_string = $_POST["query"];
    if(strlen($search_string) >= 1 && $search_string !== ' ') {
        include 'search_engine.php'
        $engine = new SearchEngine($conn);
        $results = $engine->get_search_results($search_string);
        foreach($results as $result){
          //do something
        }
    }
}
Sign up to request clarification or add additional context in comments.

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.