2011-09-14 27 views
1

ユーザが選択したオプションに基づいて、mycodeデータベースのデータでポストコード(zipcode)入力フィールドにデータを入力しようとしています。 jQueryオートコンプリートフィールドの郊外。JqueryオートコンプリートとPHP:オートコンプリートフィールドで選択されたオプションに基づいて、入力フィールドにmySQLデータベースのデータを入力する

オートコンプリートはうまく機能します。フィルタされたSuburbsリストは、ユーザーからの入力条件に基づいて取得されます。ソース参照はPHPファイルです。しかし、ユーザーの選択したオプションを使用してデータベースにコールバックして郵便番号を取得する方法を理解することはできません。おそらく、郊外と同時に、最初の呼び出しで郵便番号を取得することができます。私はすべての郵便番号を望んでいませんが、ユーザーが選択を終了するだけです。次のように

私のjQueryのは、次のとおりです( "$( '#の郵便番号')" ラインは、まだ動作しません...)

<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script> 
    <script type="text/javascript" src="js/jquery-ui-1.8.15.custom.min.js"></script> 
    <script> 
    // autocomplete 
    $(function() { 
    $("#suburbs").autocomplete({ 
    source: "allSuburbs.php", 
    minLength: 3, 
    select: function(event, ui) { 
    $('#postcodes').val(ui.item.postcode); 
    }, 
    }); 
    }); 
    </script> 

関連のhtml:

<p>Suburb</p><input class="inputText" type="text" 
    size="50" name="term" id="suburbs" maxlength="60" /></td> 
    <td><p>State</p><input class="inputText" type="text" 
    size="5" name="" id="states" maxlength="4" /></td> 
    <td><p>Postcode</p><input class="inputText" type="text" 
    size="5" name="" id="postcodes" maxlength="4" /></td> 

PHP (allSuburbs.php):

<?php 
    $con = mysql_connect("***","***","***"); 
    if (!$con) { die('Could not connect: ' . mysql_error()); } 
    $dbname = 'suburb_state'; 
    mysql_select_db($dbname); 
    $query = "SELECT name FROM suburbs"; 
    $result = mysql_query($query); 
    if (!$result) die ("Database access failed:" . mysql_error()); 
    //retrieving the search term that autocomplete sends 
    $qstring = "SELECT name FROM suburbs WHERE name LIKE '%".$term."%'"; 
    //query the database for entries containing the term 
    $result = mysql_query($qstring); 
    //loop through the retrieved values 
    while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
    { $row['name']=htmlentities(stripslashes($row['name'])); 
    $row['postcode']=htmlentities(stripslashes($row['postcode'])); 
    $row_set[] = $row['name'];//build an array 
    } 
    echo json_encode($row_set);//format the array into json data 
    mysql_close($con); 
    ?> 

私はおそらく最も有用thseのリンクを見つけました

http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/ (これは、最初に私を助けた)

http://www.jensbits.com/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/それは郵便番号または郵便番号フィールドジップコードの範囲と状態の選択に基づいてではなく、に基づいて単一の郵便番号を移入が、(これは、私の問題に最も近いです1つの郊外/都市)。

助けてください。 ありがとう、 Andrew

答えて

1

私はを正確に私のアプリに組み込んだ。 2つの郊外検索(自宅と職場の住所)があり、それぞれが一致する州と郵便番号のフィールドがあるという点で、ここでは複雑なレイヤーが追加されています。バックエンドはPHPではなくperlですが、これはクライアント側の処理には関係ありません。最終的に、バックエンドは、このようなハッシュの配列とJSON構造を返して:

[ { "id":"...", "value":"...", "state":"...", "pcode":"..." }, ... ] 

IDキーは、郊外の名前を含み、値キーは「JOLIET IL 60403」のような文字列が含まれているので、正しいデータのセットが一度選択され、異なる場所で同じ名前の複数の町/郊外の問題を解決し、それを解決するためコールバックを行います。

一度選択すると、郊外(id)、州およびpcodeの値が一致するパラメータに注入されます。

次のコードは、前の結果もキャッシュします(キャッシュは自宅と仕事の検索の間で共有されます)。

$('#hm_suburb').addClass('suburb_search').attr(
     {suburb: '#hm_suburb', pcode: '#hm_pcode', state: '#hm_state'}); 
$('#wk_suburb').addClass('suburb_search').attr(
     {suburb: '#wk_suburb', pcode: '#wk_pcode', state: '#wk_state'}); 
var sub_cache = {}; 
$(".suburb_search").autocomplete({ 
    source: function(request, response) { 
     if (request.term in sub_cache) { 
       response($.map(sub_cache[request.term], function(item) { 
        return { value: item.value, id: item.id, 
          state: item.state, pcode: item.pcode } 
       })) 
      return; 
     } 
     $.ajax({ 
      url: suburb_url, 
      data: "term=" + request.term, 
      dataType: "json", 
      type: "GET", 
      contentType: "application/json; charset=utf-8", 
      dataFilter: function(data) { return data; }, 
      success: function(data) { 
       sub_cache[request.term] = data; 
       response($.map(data, function(item) { 
        return { 
         value: item.value, 
         id: item.id, 
         state: item.state, 
         pcode: item.pcode 
        } 
       })) 
      } //, 
      //error: HandleAjaxError // custom method 
     }); 
    }, 
    minLength: 3, 
    select: function(event, ui) { 
     if (ui.item) { 
      $this = $(this); 
      //alert("this suburb field = " + $this.attr('suburb')); 
      $($this.attr('suburb')).val(ui.item.id); 
      $($this.attr('pcode')).val(ui.item.pcode); 
      $($this.attr('state')).val(ui.item.state); 
      event.preventDefault(); 
     } 
    } 
}); 
+0

ありがとう..まだまだ私のことを頭に浮かべて.. –

+0

重要なことは、あなたのAJAXのオートコンプリート*呼び出しは 'id'と' value'を返さなければなりませんが、それらの属性だけではありません。私は他のフォーム要素を変更するために、 'state'と' postcode'も返しています。 – RET

0

select関数では、別のajaxリクエストを起動したいと思うでしょう。この新しいajaxリクエストは、現在選択されている郊外をその郊外のポストコードを返す別のPHPスクリプトに送ります。このajaxリクエストに関連付けられたコールバックでは、返されたポストコードをフォームに入力します。

あなたの新しいAJAXリクエストを発射するjQuery.getを使用したいと思う: http://api.jquery.com/jQuery.get/

select: function(event, ui) { 
     $.get("postcodes.php", { suburb: $("#suburbs").val }, 
     function(postCodes) { 
     // use data in postCodes to fill in your form. 
     }, "json"); 
} 

postcodes.phpは$ _GET [ '郊外']を取るとのために郵便番号を含むいくつかのJSONの構造体を返しますその郊外。

+0

ありがとうございました..これでも問題はありません。歓声 –

0

私はそれを理解しました。みなさんありがとう。

はまた、私が見つかりました。私が何であったかにかなり近い次の後:

http://af-design.com/blog/2010/05/12/using-jquery-uis-autocomplete-to-populate-a-form/

関連のjQuery:

<script type="text/javascript"> 
    $(document).ready(function(){ 
    var ac_config = { 
    source: "SuburbStatePostcodeRetriever.php", 
    select: function(event, ui){ 
     $("#suburb").val(ui.item.locality); 
     $("#state").val(ui.item.state); 
     $("#postcode").val(ui.item.postcode); 
    }, 
    minLength:3 
    }; 
     $("#suburb").autocomplete(ac_config); 
    }); 
    </script> 

HTML:

<form action="#" method="post"> 
<p><label for="city">Suburb</label><br /> 
    <input type="text" name="city" id="suburb" value="" /></p> 
<p><label for="state">State</label><br /> 
    <input type="text" name="state" id="state" value="" /></p> 
<p><label for="zip">Postcode</label><br /> 
    <input type="text" name="zip" id="postcode" value="" /></p> 
    </form> 

PHP:

<?php 
    // connect to database 
    $con = mysql_connect("********","********","********"); 
    if (!$con) { die('Could not connect: ' . mysql_error()); } 
    $dbname = '********'; 
    mysql_select_db($dbname); 
    $initialSuburbsArray = array(); 
    $result = mysql_query("SELECT locality, postcode, state FROM ********",$con) or die (mysql_error()); 
    while($row = mysql_fetch_assoc($result)) { 
     $initialSuburbsArray[] = $row; 
    } 
    $suburbs = $initialSuburbsArray; 
    // Cleaning up the term 
    $term = trim(strip_tags($_GET['term'])); 
    // get match 
    $matches = array(); 
    foreach($suburbs as $suburb){ 
if(stripos($suburb['locality'], $term) !== false){ 
    // Adding the necessary "value" and "label" fields and appending to result set 
    $suburb['value'] = $suburb['locality']; 
    $suburb['label'] = "{$suburb['locality']}, {$suburb['postcode']} {$suburb['state']}"; 
    $matches[] = $suburb; 
    } 
    } 
    // Truncate, encode and return the results 
    $matches = array_slice($matches, 0, 5); 
    print json_encode($matches); 
    mysql_close($con); 
    ?> 

おそらくもう少し洗練が必要ですが、それがほとんどです。ありがとう。

関連する問題