Ajax多文本框搜索请求

时间:2014-05-26 08:01:07

标签: php html ajax

您好我试图让我的文本框通过AJAX在数据库中使用搜索选项。

我没有让它在多个文本框上工作,只有一个。

这是我的代码,maby你们可以帮助我让它工作。那会很棒。

PHP

<?php
$pdo = new PDO('mysql:host=localhost;dbname=records', 'root', 'l3tm31n');
$select = 'SELECT *';
$from = ' FROM overboekingen';

$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
$val = (isset($_POST['text']) ? $_POST['text'] : FALSE);

if ($val != null){
  $where = " WHERE boekingsnummer LIKE '".$val."%'";
}
elseif ($val != null){
  $where = " AND huiscode LIKE '".$val."%'";
}
else {

  if (is_array($opts) || $val){
    $where = ' WHERE FALSE';
  else {
    $where = false;
  }

}

$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);

HTML

<ul id="boekingsnummer" class="hide">                                
            <li><label>Boekingsnummer</label></li>
            <li><input type="text" name="boekingsnummer" size="20" id="boekingsnummer_1">
            <div class="suggestionsBox" id="suggestions2" style="display: none;">
            <div class="suggestionList" id="autoSuggestionsList2"></li>
</ul> 

<ul id="huiscode" class="hide">                                
            <li><label>huiscode</label></li>
            <li><input type="text" name="huiscode" size="20" id="huiscode_1" >
            <div class="suggestionsBox" id="suggestions5" style="display: none;">
            <div class="suggestionList" id="autoSuggestionsList5"></li>
</ul>

AJAX

$('#boekingsnummer_1').keyup(function(){        
    updateEmployeesText($(this).val());        
});

$('#huiscode_1').keyup(function(){        
    updateEmployeesText($(this).val());        
});

function updateEmployeesText(val){        
    $.ajax({
    type: "POST",
    url: "submit.php",
    dataType : 'json',
    cache: false,
    data: {text: val},
    success: function(records){
        $('#employees tbody').html(makeTable(records));
    }        
}); 
}

1 个答案:

答案 0 :(得分:0)

修改
我想你可能想要调用JavaScript函数和PHP脚本,如下所示: 的JavaScript

$('#boekingsnummer_1').keyup(function(){        
    updateEmployeesText($(this).val(),'boekingsnummer');        
});

$('#huiscode_1').keyup(function(){        
    updateEmployeesText($(this).val(),'huiscode');        
});

function updateEmployeesText(val,opt){        
    $.ajax({
    type: "POST",
    url: "submit.php",
    dataType : 'json',
    cache: false,
    data: {text: val, filterOpts:opt},
    success: function(records){
        $('#employees tbody').html(makeTable(records));
    }        
}); 
}

PHP:

$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
$val = (isset($_POST['text']) ? $_POST['text'] : FALSE);

if (($val != FALSE) && ($opts == "boekingsnummer")){
  $where = " WHERE boekingsnummer LIKE '".$val."%'";
}elseif (($val != FALSE) && ($opts == "huiscode" )){
  $where = " WHERE huiscode LIKE '".$val."%'";
}