jQuery的自动完成不工作连接到MySQL数据库 [英] jQuery autocomplete not working connected to mySQL database

查看:197
本文介绍了jQuery的自动完成不工作连接到MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个是工作完全没自动完成表单。我离开我的笔记本电脑回来,现在不工作了。

I have an autocomplete form that was working completely fine. I leave my laptop and come back and now it doesn't work anymore.

我的数据库名为wallettest

My database is named wallettest

我的表名为人口有4列:
ID,位置,蛞蝓,人口。

My table is named population and has 4 columns: Id, location, slug, Population.

我有3个文件:index.php文件的script.js和ajax_refresh.php

I have 3 files: index.php, script.js and ajax_refresh.php.

做一些测试,似乎它没有访问我的ajax_refresh.php这我连接到我的数据库。因此,从那里,我决定把我的ajax_refresh.php在我的index.php文件。好了,现在我连接到我的数据库,但得到错误(我不知道为什么它不会连我摆在首位,我有正确的语法在我的文件:

Doing some testing, it seems it's not accessing my ajax_refresh.php which connects me to my database. So from there, I decided to put my ajax_refresh.php in my index.php file. Well, now I'm connected to my database but getting errors (I don't get why it wouldn't connect me in the first place, I had the right syntax in my file:

js file:"$.ajax({
            url: "ajax_refresh.php",

不管怎么说,文件现在看起来是这样的,我得到下面的错误是:

Anyways, file now looks like this and the error I get is below:

的index.php:

index.php:

<?php
// PDO connect *********
//CHECK TO SEE IF CONNECTION IS MADE
 $db = mysql_connect("localhost","root","butthead"); 
 if ($db) {
 echo("- Connection to database successful -");
 }
 else if (!$db) {
 die("Database connection failed miserably: " . mysql_error());
 }


function connect() {
    return new PDO('mysql:host=localhost;dbname=wallettest', 'root', 'butthead', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
} 


$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM population WHERE slug LIKE (:keyword) ORDER BY population DESC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
    // put in bold the written text
    $slug = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['slug']);
    // add new option
    echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['slug']).'\')">'.$slug.'</li>';
}

// END AJAX_REFRESH.PHP
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Autocomplete using PHP/MySQL and jQuery</title>
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>


<body>
    <div class="container">
        <div class="header">

        </div><!-- header -->
        <h1 class="main_title">Autocomplete using PHP/MySQL and jQuery</h1>
        <div class="content">
            <form>
                <p>Table consists of : ID, Location, Slug, Population </p>
                <br><br>
                <div class="label_div">Search for a Slug : </div>
                <div class="input_container">
                    <input type="text" id="slug" onkeyup="autocomplet2()">
                    <ul id="list_id"></ul>
                </div>
            </form>
            <br><br><br><br>
            <p>List will be ordered from Highest population to lowest population (Top to bottom)</p>
                <br><br>
        </div><!-- content -->    
        <div class="footer">
            Powered by Jason's Fingers</a>
        </div><!-- footer -->
    </div><!-- container -->
</body>
</html>

的script.js:

script.js:

// autocomplete : this function will be executed every time we change the text
function autocomplet2() {
    var min_length = 3; // min caracters to display the autocomplete
    var keyword = $('#slug').val();
    if (keyword.length >= min_length) {
        $.ajax({
            url: 'ajax_refresh.php',
            type: 'POST',
            data: {keyword:keyword},
            success:function(data){
                $('#list_id').show();
                $('#list_id').html(data);
            }
        });
    } else {
        $('#list_id').hide();
    }
}

// set_item : this function will be executed when we select an item
function set_item(item) {
    // Changes input to the full name on selecting
    $('#slug').val(item);
    // Hides list after selection from list
    $('#list_id').hide();
}

function change()

错误:

推荐答案

有很多有趣的事情在你的code:

There are many things funny in your code:


  1. 缺少形式方法(默认为GET)。

  2. 混合的的mysql _ * 和PDO API的。在您使用您可以删除整个条件 mysql_connect()函数因为你从来没有使用的连接( $分贝)创建那里。

  3. 从输入元素缺少名称属性:

  1. Missing form method (default is GET).
  2. Mixing the mysql_* and PDO API's. You can remove the entire conditional where you use mysql_connect() as you never ever use the connection ($db) created there.
  3. Missing name attribute from your input element:

&LT;输入类型=文本ID =鼻涕虫NAME =关键词的onkeyup =autocomplet2()&GT;

什么是产生错误的是这条线在你的PHP:

What is generating the error is this line in your PHP:

$keyword = '%'.$_POST['keyword'].'%';

当您最初加载页面的变量 $关键字没有定义,因为 $ _ POST 阵一直没有组。

When you initially load the page the variable $keyword is not defined because the $_POST array has not been set. The way that you prevent that is by checking to see if the array has been set before assigning a value to the variable:

if(isset($_POST)) {
    $keyword = '%'.$_POST['keyword'].'%';
    // other code relying on $keyword being set should go here
}

中注意上面的code中的注释。的任何的code依靠关键字被设置,比如你的数据库查询,应该是有条件的内部。有一个在运行code。如果变量没有设置没有意义。

Take note of the comment in the code above. Any code relying on the keyword being set, such as your database query, should be inside of the conditional. There is no sense in running that code if the variable is not set.

最后,您的code组织将开始,当你决定扩展你所拥有的在这里变得难以管理。考虑相互分隔的PHP,HTML和JS,以便更容易管理。

Finally, your code organization is going to start to become hard to manage when you decide to expand what you have here. Consider separating the PHP, HTML and JS from each other to allow for easier management.

这篇关于jQuery的自动完成不工作连接到MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆