简体   繁体   English

PHP Ajax两次返回HTML

[英]PHP Ajax returning HTML twice

I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. 我有一个PHP / Ajax函数,可在文本框中返回具有给定字符的国家/地区列表。 Ofcourse Ajax updates this list everytime the textbox gets edited. 当然,每次编辑文本框时,Ajax都会更新此列表。

Index.PHP calls all the other files, classes and HTML. Index.PHP调用所有其他文件,类和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. 但是,当文本框得到更新时,Ajax将POST变量发送到index.PHP,因为这是调用类名SearchEngine的Search.PHP文件的地方。 But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice. 但是因为他将其发送到index.php,所以所有内容都会不断重新加载,并且HTML将返回两次。

Index.php 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. 我目前正在将我所有的代码都转换为PDO并对其进行完善,但这将在以后提供。

Search.PHP 搜索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 最后是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 注意:HTML是从Index.php内部调用的“ page”类返回的

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 编辑:建议将我直接将ajax url指向AutoComplete.php的新文件

AutoComplete.PHP 自动完成

Please explain what should be in the file and why. 请说明文件中应包含什么以及原因。 I am clueless. 我无能为力。

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: 基本上,只需在您的Ajax调用中添加一个参数,以告诉index.php它被Ajax调用,然后将if语句包装在打印出实际索引页面的两行周围:

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

and in your Ajax call: 并在您的Ajax电话中:

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. 或者制作另一个php页面,例如ajaxsearch.php,该页面与index.php相同,但缺少这两行,然后在Ajax调用中调用它。

First thing (this is a sample, not tested yet) 第一件事(这是一个示例,尚未测试)

autocomplete.php 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 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 :) 祝你好运:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM