初学者AJAX搜索功能

时间:2014-03-09 11:33:57

标签: javascript php jquery ajax

我正在研究即时搜索功能,目前我无法将变量从JS传递到PHP文件。一旦得到查询结果,我也不确定该怎么做。任何帮助都会很棒。这是我目前的立场。

ERROR

Undefined index: partialSearch in \php\search.php on line 4

test.php的

<?php
session_start();
?>  
<!DOCTYPE html>
<html lang="en"> 
<head>

<meta charset="utf-8">
<title>AJAX SEARCH</title>

<link rel="stylesheet" href="stylesheets/base.css">
<link rel="stylesheet" href="stylesheets/skeleton.css">
<link rel="stylesheet" href="stylesheets/layout.css">

<script type="text/javascript"     src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function search(partialSearch){
$.ajax({url:"PHP/search.php",data: partialSearch,success:function(result){
$("#results").html(result);
 }});
 };
</script>

</head>
<body>
<div class="container">

    <div class="one-third column index">
    <h3>Search Our Site</h3>
    <p>Simply type into the search bar below the video, article you are looking for.</p>

    <input type="text" name="partialSearch"onkeyup="search(this.value)"/>
    <div id="results"></div>

    </div>

</div>

</body>
</html>

的search.php

<?php
include 'config.php';

$partialSearch = $_POST['partialSearch'];

$stmt = $mysqli->prepare("SELECT Name FROM videos WHERE Name LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($Name);
while ($row = $stmt->fetch()) {
$searchResults[] = $Name;
echo "<div>".$searchResults."</div>";
}

?>

3 个答案:

答案 0 :(得分:1)

你应该改变

data: partialSearch

data: {partialSearch: partialSearch} // or {"partialSearch": partialSearch}, which is the same

其中partialSearch是数据的索引名称。

答案 1 :(得分:0)

1。)你没有告诉jQuery发帖,例如

    $.ajax({ type: "POST", ... });

您也可以使用简写“.post”

    $.post{url:"PHP/search.php",data: partialSearch,success:function(result){ $("#results").html(result);

2。)PHP认为是一个命名的POST变量。所以你的partialSearch必须是一个像这样的对象

    partialSearch = { partialSearch : "I AM your variable, NOT the object holding me !!!" }

答案 2 :(得分:0)

默认情况下,$.ajax来电会发送 GET 请求,因此您的$_POST在.php文件中无效,除非您指定..type:"POST"..变量在$.ajax(..设置中。

其次,你需要改变这个:

$.ajax({url:"PHP/search.php",data: partialSearch,success:function(result){

到此:

$.ajax({url:"PHP/search.php",type:"POST",data:{partialSearch:partialSearch},success:function(result){

将变量对象传递给发送是完全可以的。