0

I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.

Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.

Index.php

<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");

$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";

$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);

$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn); 
?>

Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.

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 = $_POST['query'];
        }

        //$search_string = mysql_real_escape_string($search_string);

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

}
?>

And as final the Javascript

$(document).ready(function() {

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

    if(query_value !== ''){
        $.ajax({
            type: "POST",
            url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
            data: { query: query_value },
            cache: false,
            success: function(html){
                $("ul#results").html(html);
            }
        });
    }

    return false;
}

$("input#search").keyup(function() {
    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));
    };
});
});

note: HTML is being returned from the "page" class called inside Index.php

How do i not let everything get called twice?

Thank you,

EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php

AutoComplete.PHP

Please explain what should be in the file and why. I am clueless.

13
  • Don't send the ajax to index.php from index.php That's like making an infinite loop. Commented Jul 7, 2014 at 21:45
  • @developerwjk Well, how would i start to solve this problem? because what you told me is what i already figured out. Commented Jul 7, 2014 at 21:47
  • 1
    Use different scripts for serving AJAX and page display. Or have your script check $_SERVER['REQUEST_METHOD'] -- if it's GET, it displays the page, if it's POST it returns the AJAX response. Commented Jul 7, 2014 at 21:48
  • 1
    Create another file called autocomplete.php for instance there you can put the query to retrieve the results and make your ajax call without any problem Commented Jul 7, 2014 at 21:50
  • 1
    different scripts = new php file :) Commented Jul 7, 2014 at 21:51

2 Answers 2

1

Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:

if(!isset($_REQUEST['calledByAjax']))
{
  $IndexPage = new page();
  echo $IndexPage->render();
}

and in your Ajax call:

data: { query: query_value, calledByAjax: 'true'  },

Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.

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

1 Comment

Ignore my last comments, that was just a simple mistake by myself. Thank you so much this has worked for me! thank you for having patience with me and explaining to me.
0

First thing (this is a sample, not tested yet)

autocomplete.php

<?php
$search_string = $_POST['query'];

$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);
?>

autocomplete.js

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

if(query_value !== ''){
    $.ajax({
        type: "POST",
        url: "autocomplete.php", //Here change the script for a separated file
        data: { query: query_value },
        cache: false,
        success: function(html){
            $("ul#results").html(html);
        }
    });
}

return false;
}

$("input#search").keyup(function() {
    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();
        search(); // call the function without setTimeout 
    }
  });
 });

Have luck :)

9 Comments

Alright now what should i do with Search.PHP to me it looks completely useless and i am just altering a few bits of code from that file?
And how should i call autocomplete since its not a class anymore etc.
we dont know that you had a search.php file, you just put the index.php file, you must give more details to get a right answer :)
But.. in my question i stated the name of every file and under the name a block of code with everything inside of it. The block code of autocomplete.php is nearly the same as search.php
The only file i didnt give was HTML_Page.class.PHP and the Style.css for obvious reasons. since one is almost pure HTML and the other css
|

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.