使用PHP,AJAX和jQuery搜索MySQL数据库

I'm trying to write a very simple search system where the user searches for a product in a small database of only about 50 entries. I'm trying to use jQuery and AJAX to send the search query to an external PHP script which performs the actual MySQL query and returns a list of results which I can then append on to the search page.

I have this for my search page:

<form method="get">
   <input type="text" id="searchbox" name="search"/>
   <button class="button" id="searchbutton">Search</button>
</form>


<script type="text/javascript">

    function makeAjaxRequest() {
    $.ajax({
        url: 'search_execute.php',
        type: 'get',
        datatype: 'html',
        data: {search: $('#searchbox').val()},
        success: function(response) {
            alert("Success!");
        }, error : function() {
            alert("Something went wrong!");
       }
    });


});

//capture user clicking button
$('#searchbutton').click(function(){
     makeAjaxRequest();
});

//capture user pressing 'return'
$('form').submit(function(e){
    e.preventDefault();
    makeAjaxRequest();
});      

</script>

Naturally here I'm just using alerts for debugging.

Here's my PHP from the external script:

<?php
require('connection.php');

if(isset($_GET['search'])) {
    $search = $_GET['search'];
    echo $search;
    $stmt = $dbc->prepare("SELECT product_id, product_name FROM products WHERE product_name LIKE '%' ? '%'");
    $stmt -> execute(array($search));
    $num = $stmt->rowCount();
}
if ($num == 0){
    echo "<p>Sorry, no products matched your search</p>";
} else {
    if ($num == 1){
            echo '<p>We have found 1 product that matches your search terms. Please click the link to visit the product page.</p>';
        } else {
            echo '<p>We have found '.$num.' products that match your search terms. Please click a link to visit the product page.</p>';
        }
        echo '<ul class="products>';
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            echo '<li><h3><a href="product.php?id='.$row['product_id'].'">'.$row['product_name'].'</a></h3></li>';
        }
    echo '</ul>';
}

?>

The problem is, it fails, and it fails silently. I get no alert either way and no errors in the console, or Firebug. The PHP works fine in isolation, but when I use the search page - bupkus.

EDIT: I've moved the event handlers outside the makeAjaxRequest function but still no dice.

drxvjnx58751
drxvjnx58751 他们偶尔会改变,我希望它在任何情况下都是面向未来的。
接近 6 年之前 回复
dongzhan5286
dongzhan5286 偏离你的问题,你可能有理由不这样做,但如果它只是〜50个产品那么你真的需要在每次搜索时查询数据库吗?如果产品数量很少,它们不太可能发生太大变化?因此,可能将它们存储在您的JS中,而不是发送ajax请求并在每次搜索时点击数据库对您有益吗?只是一个想法。
接近 6 年之前 回复
dongquanlin1885
dongquanlin1885 注意到并改变了,谢谢。
接近 6 年之前 回复
douci1677
douci1677 event.preventDefault();应该是e.preventDefault();
接近 6 年之前 回复

4个回答



您的Javascript代码不正确,您在函数 makeAjaxRequest </ code>中添加了事件函数,因此它永远不会 调用。 它应该是</ p>

 &lt; script type =“text / javascript”&gt; 
$(document).ready(function(){
function makeAjaxRequest(){

$ .ajax({
url:'search_execute.php',
type:'get',
datatype:'html',
data:{search:$('#searchbox')。val( }},
成功:函数(响应){
alert(“成功!”);
},
错误:function(){
alert(“出错了!”);
} \ n});
}

$('#searchbutton')。click(function(){
makeAjaxRequest();
});

$('form')。submit(function (e){
e.preventDefault();
makeAjaxRequest();
});
});

</ code> </ pre>
</ div>

展开原文

原文

Your Javascript code is not correct, the event functions you have added inside the function makeAjaxRequest and hence its never called. It should be as

<script type="text/javascript">
$(document).ready(function(){
    function makeAjaxRequest() {
        $.ajax({
            url: 'search_execute.php',
            type: 'get',
            datatype: 'html',
            data: {search: $('#searchbox').val()},
            success: function(response) {
                    alert("Success!");
            }, 
            error : function() {
                    alert("Something went wrong!");
            }
        });
    }

    $('#searchbutton').click(function(){
            makeAjaxRequest();
    });

    $('form').submit(function(e){
            e.preventDefault();
            makeAjaxRequest();
    });
});          

dph6308
dph6308 得到它了! 想想我在某个地方错过了一个括号,但控制台没有因某种原因报告它。 谢谢您的帮助。
接近 6 年之前 回复
dongshen3352
dongshen3352 是的,它作为查询字符串发送正确的语法,即search_execute.php?search = whatever。 没有报告JS错误。 然而,我所获得的是地址栏中的URL更改为包括查询字符串,例如, search.php中?搜索=什么的。 即使它实际上正确地将请求发送到search_execute.php。
接近 6 年之前 回复
dounieyan2036
dounieyan2036 检查浏览器开发工具是否将查询字符串作为查询字符串发送。 检查生成的实际网址。 另请参阅开发工具中是否存在一些JS错误。
接近 6 年之前 回复
douhoujun9304
douhoujun9304 谢谢 - 我改变了这一点,但似乎没有任何区别。
接近 6 年之前 回复



您的括号在JavaScript代码中有点奇怪。 它现在的样子,事件绑定在makeAjaxRequest()函数内部,因此处理程序永远不会绑定到事件,直到首次调用该函数。 当然,该函数只能从事件处理程序中调用,因此它永远不会被调用。</ p>

要解决此问题,只需将绑定复制粘贴到函数外部即可。</ p>

您也可以将第一个绑定更改为</ p>

  $('#searchbutton')。click(makeAjaxRequest); 
</ code> </ pre>

获得较小的性能提升。</ p>
</ div>

展开原文

原文

Your brackets are kind of weird in the JavaScript code. The way it looks right now, event bindings are inside the makeAjaxRequest() function, so the handlers never get bound to the events until the function is first called. Of course, the function is only ever called from the event handlers, so it's never called.

To fix this, just copy-paste the bindings outside the function.

You can also change the first binding to

$('#searchbutton').click(makeAjaxRequest);

for a small performance gain.

dongzz4545
dongzz4545 检查Abhik的答案。 您需要在$(document).ready(function(){})中绑定事件处理程序。 您可以将makeAjaxCall()函数定义保留在外部。
接近 6 年之前 回复
douqin6785
douqin6785 谢谢 - 我已经做到了但仍然没有。
接近 6 年之前 回复



你应该使用你的查询,如</ p>

  $ q ='%'。$ 搜索。  '%'
$ stmt = $ dbc-&gt; prepare(“SELECT product_id,product_name FROM products WHERE product_name LIKE?”);
$ stmt-&gt; execute(array($ q));
</ code > </ pre>
</ div>

展开原文

原文

You should use your query like

$q = '%' .$search. '%'
$stmt = $dbc->prepare("SELECT product_id, product_name FROM products WHERE product_name LIKE ?");
$stmt->execute(array($q));

duandao2083
duandao2083 好的,现在有意义;)
接近 6 年之前 回复



 &lt; script type =“text / javascript”&gt; 
$(document).ready(function(){

var sval = $('#searchbox')。val();
var datastring =“search =”+ sval;

$('#searchbutton')。click(function(){
$ .ajax({
url:'search_execute.php',
type:'get',
datatype:'html',
data:datastring,
success:function(response){
alert(“ 成功!“);
},错误:function(){
alert(”出错了!“);
}
});
});
});
&lt; / script&gt ;
</ code> </ pre>


在php文件中更改sql </ p>
</ blockquote>

  $ stmt  = $ dbc-&gt; prepare(“SELECT product_id,product_name FROM products WHERE product_name LIKE'%”。$ search。“%'”); 
</ code> </ pre>
</ div>

展开原文

原文

<script type="text/javascript">
$(document).ready(function(){
    var sval = $('#searchbox').val();
    var datastring = "search="+sval;

    $('#searchbutton').click(function(){
        $.ajax({
            url: 'search_execute.php',
            type: 'get',
            datatype: 'html',
            data: datastring,
            success: function(response) {
                alert("Success!");
            }, error : function() {
                alert("Something went wrong!");
           }
        });
    });
});
</script>

In php file change sql

$stmt = $dbc->prepare("SELECT product_id, product_name FROM products WHERE product_name LIKE '%".$search."%' ");

立即提问
相关内容推荐