2017-02-17 7 views
0

Customer textfield with autocomplete from databasePHP&jQueryのは -

私が入力中のテキストで開始し、顧客を表示するオートコンプリートを持つ1つの顧客テキストフィールドを作成することに成功したオートコンプリートは、データベースから取得したデータの異なるリストを持つ二つの異なるテキストフィールドを作成します。 1つのテキストフィールド

   <meta charset="utf-8"> 
      <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> 
      <script src="//code.jquery.com/jquery-1.10.2.js"></script> 
      <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
      <script> 
      $(function() { 
      $("#customer").autocomplete({ 
       source: "../phpfiles/search.php", 
      }); 
      }); 
      </script> 



     <div class="ui-widget"> 
     <!-- action='./../customer_report_request' --> 
      <form id="customer_report_request" name="customer_report_request" method="post"> 
       <table> 
        <tr> 
         <th colspan='2'>Search Customer</th> 
        </tr> 
        <tr> 
         <td> 
          <label>Customer: </label> 
          <input name="customer" id="customer" value='' required> 
         </td> 
         <td> 
          <label>Submit: </label> 
          <input value="Send" name="send_customer_request" type="submit" id="send_customer_request"> 
         </td> 
        </tr> 
       </table> 
      </form> 
     </div> 

     <?php 
      //Display the list of customer details 
      if(isset($_POST['send_customer_request'])) 
      { 
       include 'db.php'; //connection 

       $query = "SELECT * FROM customer WHERE Company_Name = '".$_POST['customer']."'"; 
       $customer_result = $db->query($query); 
       $count_customer = $customer_result->num_rows; 
       if($count_customer>0) 
       { 
        echo"<div>"; 
        echo "<table>"; 
        echo"<tr>"; 
        echo"<th>Company_Name</th>"; 
        echo"<th>VAT_Registration</th>"; 
        echo"<th>Contact_First_Name</th>"; 
        echo"<th>Contact_Last_Name</th>"; 
        echo"<th>Email</th>"; 
        echo"</tr>"; 

        while ($row = $customer_result->fetch_assoc()) 
        { 
         echo"<tr>"; 
         echo"<td>".$row['Company_Name']."</td>"; 
         echo"<td>".$row['VAT_Registration']."</td>"; 
         echo"<td>".$row['Contact_First_Name']."</td>"; 
         echo"<td>".$row['Contact_Last_Name']."</td>"; 
         echo"<td>".$row['Email']."</td>"; 
         echo"</tr>"; 
        } 
        echo "</table>"; 
        echo"</div>"; 
       } 
       $db->close(); 
      } 

     ?> 

ため

のindex.php Search.php 1つのテキストフィールド

  <?php 
     $dbHost = 'localhost'; 
     $dbUsername = 'bobo'; 
     $dbPassword = 'rodnik'; 
     $dbName = 'training'; 

     //connect with the database 
     $db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName); 

     //get search term 
     $searchTerm = $_GET['term']; 

     //get matched data from customer table 

     $query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with 


     while ($row = $query->fetch_assoc()) { 
      $data[] = $row['Company_Name']; 
     } 
     //return json data 
     echo json_encode($data); 
     ?> 

のための問題は、私は他のに対応するために単一の検索PHPファイルを使用したいですクエリ。たとえば :ワードが連絡先のテキストフィールドに入力された場合

  • 、クエリは、クエリ、単語が顧客テキストフィールドに入力された場合
  • 「....コンタクトSELECT * FROM」 になります "SELECT * FROM Customer ...."

これを達成するためにindex.phpとsearch.phpの両方が変更されました。

index.phpの中の修飾部分

jQueryの変数は、COMPONENT_NAMEを定義しました。 index.phpファイルから、お客様のtexfieldは、search.phpファイルに変数を送信し、POSTメソッドを使用して、その変数を識別して照会の目的で使用できるようにします。

連絡先テキストフィールドは、index.phpファイルまたは別のPHPファイル内の同じ形式のいずれかにすることができます。

   <script> 
       $(function() { 
       $("#customer").autocomplete({ 
        var component_name= "customer"; 

        source: "../phpfiles/search.php", 
        minLength: 1, 
        change: function(event, ui) 
        { 
         $.post("../phpfiles/search.php", data{post_data: component_name}); 
        } 
       }); 
       }); 
      </script> 

修正search.php

 <?php 
    $dbHost = 'localhost'; 
    $dbUsername = 'bobo'; 
    $dbPassword = 'rodnik'; 
    $dbName = 'training'; 
    //connect with the database 
    $db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName); 
    //get search term 
    $searchTerm = $_GET['term']; 
    //get matched data from skills table 

    $query=""; 
    if($_POST['post_data']=="customer") 
    { 

     $query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with 
     while ($row = $query->fetch_assoc()) 
     { 
      $data[] = $row['Company_Name']; 
     } 

     //return json data 
     echo json_encode($data); 
    } 


    ?> 

誰もがこれを達成するために私を助けることができますか?

私はjqueryの-UIとjQuery APIの部品のため、これらのリンクを使用:これは私が願って少し複雑広告かもしれ

  • api.jquery.com
  • jqueryui.com
+0

ようこそスタックオーバーフロー。 index.phpで検索結果を編集するときにこれを使用していますか?あなたがそれを提示したやり方を少し混乱させます。私は両方のテキストフィールドを選択するためにクラスセレクタを使用します。そして、あなたの 'ソース'では、どのフィールドが使用されているのかを判断し、それに基づいて検索を実行できます。 – Twisty

答えて

0

を助けになる。あなたの例は、あなたのDBにサンプルデータやスキーマを提供していないので、私はいくつかの推測をしなければなりませんでした。あなたは調整する必要があります。

あなたは別の入力フィールドを持っている場合、あなたが持っている可能性が考えてみましょう:

HTML

<div class="ui-widget"> 
    <form id="customer_report_request" name="customer_report_request" method="post"> 
    <table> 
     <tr> 
     <th colspan='2'>Search Customer</th> 
     </tr> 
     <tr> 
     <td> 
      <label>Customer: </label> 
      <input class="entry-field" name="customer" id="customer" value='' required> 
     </td> 
     <td> 
      <label>Submit: </label> 
      <input value="Send" name="send_customer_request" type="submit" id="send_customer_request"> 
     </td> 
     </tr> 
     <tr> 
     <td> 
      <label>Contact: </label> 
      <input class="entry-field" name="contact" id="contact" value='' required> 
     </td> 
     <td> 
      <label>Submit: </label> 
      <input value="Send" name="send_customer_request" type="submit" id="send_ccontact_request"> 
     </td> 
     </tr> 
    </table> 
    </form> 
</div> 

はJavaScript

$(function() { 
    $(".entry-field").autocomplete({ 
    source: function(req, resp) { 
     // determine which field we're working with 
     var type = $("this").attr("id"); 
     // collect the entry in the field 
     var term = req.term; 
     // Prepare our response array 
     var responses = []; 
     // PErform POST Request to our Search and accept JSON results 
     $.ajax({ 
      url: "../phpfiles/search.php", 
      data: { 
       t: type, 
       q: term 
      }, 
      type: "POST", 
      dataType: "JSON", 
      success: function(results) { 
       $.each(results, function(key, val) { 
       responses.push(val); 
       }); 
      }); resp(responses); 
     }, 
     minLength: 1 
    } 
    }); 

    $("#customer_report_request").submit(function(e) { 
    e.preventDefault(); 
    if ($("#customer").val().length) { 
     // perform POST to a PHP search for that specific customer details 
    } else { 
     // performn a post to a PHP search for that specific contact details 
    } 
    // populate result DIV on page with resulting data from POST 
    }); 
}); 

PHP:search.php

<?php 
$dbHost = 'localhost'; 
$dbUsername = 'bobo'; 
$dbPassword = 'rodnik'; 
$dbName = 'training'; 
//connect with the database 
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName); 
// get search query 
$searchTerm = $_POST['q']; 
// get search type 
$searchType = $_POST['t']; 
//get matched data from customer table 
if($searchType == "customer"){ 
    /* create a prepared statement */ 
    $stmt = $mysqli->prepare("SELECT * FROM customer WHERE Company_Name LIKE '?%'"); 

} else { 
    /* create a prepared statement */ 
    $stmt = $mysqli->prepare("SELECT * FROM customer WHERE Contact_Name LIKE '?%'"); 
} 
/* bind parameters for markers */ 
$stmt->bind_param("s", $searchTerm); 
/* execute query */ 
$stmt->execute(); 
/* instead of bind_result: */ 
$result = $stmt->get_result(); 
while ($row = $results->fetch_assoc()) { 
    if($searchType == "company"){ 
     $data[] = $row['Company_Name']; 
    } else { 
     $data[] = $row['Contact_Name'] 
    } 
} 
//return json data 
header('Content-Type: application/json'); 
echo json_encode($data); 
?> 

ですから、多くのことが起こっています。あなたのPHPで始まります。 SQLインジェクションに脆弱でしたので、私はMySQLi Prepareを使って物事を守りました。このスクリプトにデータが掲載されることを期待しています。条件はquerytypeです。タイプがない場合は、デフォルトを設定できます。 queryの小切手を追加することもできますが、常に1文字にする必要があります。

このデータは、sourceオプションの関数メソッドを使用して検索スクリプトに渡されます。詳細:http://api.jqueryui.com/autocomplete/#option-source

機能:コールバックは、最も柔軟性が高く、データソースをオートコンプリートに接続するために使用できます。

  • requestオブジェクト、テキスト入力現在値を指す単一term性を有する:コールバックは2つの引数を取得します。たとえば、都市のフィールドに「new yo」と入力すると、オートコンプリートtermは「new yo」になります。
  • responseコールバック.1つの引数が必要です:ユーザーに示唆するデータ。このデータは、提供されたtermに基づいてフィルタリングされるべきであり、単純なローカルデータについて上述したいずれかのフォーマットにすることができる。 requestの間にエラーを処理するカスタムソースコールバックを提供するときは重要です。エラーが発生した場合でも、必ずresponseコールバックをコールする必要があります。これにより、ウィジェットは常に正しい状態になります。

だからこれで、私たちは$.ajax()通話に追加し、errorコールバックを利用することができます。基本的には、空の配列をresponseに送り返してしまいます。

検索条件をPHPに送信すると、JSON配列データが返されます。これを独自の配列にパイプしてresponseに送り返すと、結果のリストが表示されます。

これはまだちょっと大変なことですが、これはユーザーの慣れていればOKです。それをスリムにして、結果を分類することもできます。この方法で、1つの検索フィールドを持つことができます。また、何かが選択されたり、フィールドが変更されたりすると、AJAXを使用して、データベースからすべてのデータを取得する別のPHPの詳細を取得することができます。これにより、ページが再び読み込まれるのを待つ必要がなくなります。

私はこれがあなたの質問に答えることを願っています。周りを検索し続けると、たくさんの答えがあります。時として、大きな問題を小さな問題に分割するのは、全体を取り組むよりも簡単です。