2011-12-17 2 views
0

저는 Ajax PHP MySQL 라이브 검색을 통해 기본적으로 MySQL 데이터베이스에서 식품 항목을 추출하고 드롭 다운 목록에 표시합니다 (사용자가 검색어, 한 줄에 하나의 항목을 입력 할 때). Google에서 검색하는 것처럼Ajax PHP 라이브 검색 - 두 번째 단계가 필요합니다.

내가 필요한 것은 사용자가 특정 결과 항목을 클릭 할 수있게하고, 클릭 한 항목 바로 아래에서 열거 할 수있는 몇 가지 라디오 버튼이있는 상자로, 해당 특정 음식의 다양한 양의 옵션을 나열합니다 목. 그러면 사용자는 금액 옵션을 선택하고 제출을 클릭하여 선택 사항을 저장할 수 있습니다.

나는 PHP와 MySQL, HTML을 잘 알고 있지만, JS는 약간의 도전 과제이므로, 답을 상세히 설명해 주시면 감사하겠습니다.

  1. HTML 검색 서 양식 :/검색 폼 w 같은 페이지에

    <input type="text" size="30" name="food_name" id="q" value="" onkeyup="sendRequest(this.value);" autocomplete="off"/> 
    
  2. 아약스 코드 :

    다음은 내가이 시점에서 가지고있는 일부 코드 조각입니다

    function createRequestObject() { 
    
        var req; 
    
    if(window.XMLHttpRequest){ 
        // Firefox, Safari, Opera... 
        req = new XMLHttpRequest(); 
    } else if(window.ActiveXObject) { 
        // Internet Explorer 5+ 
        req = new ActiveXObject("Microsoft.XMLHTTP"); 
    } else { 
        alert('Problem creating the XMLHttpRequest object'); 
    } 
    
    return req; 
    
    } 
    
    // Make the XMLHttpRequest object 
    var http = createRequestObject(); 
    
    function sendRequest(q) { 
    
    // Open PHP script for requests 
        http.open('get', 'checkfoods.php?q='+q); 
        http.onreadystatechange = handleResponse; 
        http.send(null); 
    
        } 
    
        function handleResponse() { 
    
        if(http.readyState == 4 && http.status == 200){ 
    
        // Text returned FROM the PHP script 
        var response = http.responseText; 
    
        if(response) { 
        // UPDATE ajaxTest content 
        document.getElementById("searchResults").innerHTML = response; 
        } 
    
        } 
    
        } 
    
  3. FOOD_DES라는 테이블을 MySQL로 가져 와서 가져 오는 PHP 스크립트 식품의 드롭 다운 목록을 채우는 결과를 백업 :

    include 'my-food-dtabase.php'; 
    
        $searchQry = isset($_GET['q']) ? mysql_real_escape_string($_GET['q']) : false; 
    
        if ($searchQry) { 
        $searchString = $_GET['q']; 
    
        $sql = mysql_query("SELECT NDB_No, FdGrp_Cd, Long_Desc FROM FOOD_DES WHERE Long_Desc LIKE '%".$_GET['q']."%' ORDER BY Long_Desc ASC"); 
    
        if($searchString != NULL) { 
    
        while($row = mysql_fetch_assoc($sql)) { 
        echo "<span id=foodlist><a href=calorie-counter-serving.php?NDB_No=".$row['NDB_No'].">".$row['Long_Desc']."</a><br /></span>"; 
    } 
    } 
    
        if(mysql_num_rows($sql) == 0) { 
        echo "<span class=medium_white>Food item not found. Try a different name or keyword.</span>"; 
        } 
        } 
    
+0

http://www.cs.arizona.edu/~mccann/indent_c.html#One –

+0

이 작업을 할 때 AJAX 요청/응답을 볼 수 있는지 확인하십시오 - 그것은 엄청난 도움이됩니다. 크롬이 기본적으로 가지고 있거나 Firefox + Firebug가 좋습니다. – halfer

답변

3

이 반드시 완전한 대답하지만, 올바른 방향으로 포인터가 아닙니다.

jQuery를 순수 자바 스크립트로 사용하면 많은 시간과 노력을 절약 할 수 있습니다. 또한 자신의 Ajax API과 함께 2 단계를 몇 줄로 줄일 수 있습니다. 여기에 tutorial on its Ajax system이 있습니다. 훨씬 쉬워졌습니다!

jQuery UI는 사용자 인터페이스를 작성하는 데 도움이되는 jQuery의 훌륭한 확장 프로그램이며 대화 상자 위젯입니다. 나는 'Modal form' dialog example이 '새로운 사용자 생성'버튼을 클릭 할 때 달성하고자하는 것과 매우 흡사하다고 생각합니다. 그들이 어떻게했는지 보려면 '소스보기'를 클릭하십시오.

3 단계에서 볼 수 있듯이 쿼리를 살균하지는 않습니다. $ _GET [ 'q']이 (가) 쿼리 문자열에 던져지고 있습니다. 위의 몇 줄을 이미 정의한 $ searchQry로 바꾸어야합니다.

+0

+1, 예, 확실히 JS 라이브러리. Google은 기본적으로 요청 당 몇 KB를 절약하기 위해 모든 것을 수행합니다. 이러한 고공의 높이에서 작동하지 않는 사람은 jQuery/MooTools/Prototype 등을 사용해야합니다. – halfer

0

http://koding.info/2013/07/ajax-search-box-php-mysql-jquery/ 저는 Wordpress 데이터베이스를 사용하는 데모 라이브 검색 응용 프로그램을 구현했습니다. 보세요. 도움을 받으실 수 있습니다.

+1

[링크 전용 답변] (http://meta.stackoverflow.com)/tags/link-only-answers/info)는 권장하지 않습니다. 따라서 SO 솔루션은 솔루션 검색의 종단점이어야합니다. 링크를 참조 용으로 유지하면서 독립형 시놉시스를 여기에 추가하는 것을 고려해보십시오. – kleopatra

0

다음은 Ajax, PHP 및 JQuery로 할 수있는 작업입니다. 희망이 도움이되거나 당신에게 시작을 제공합니다.

여기에서 라이브 데모 및 소스 코드를 참조하십시오.

http://purpledesign.in/blog/to-create-a-live-search-like-google/

는 검색 상자를 만들고이 같은 입력 필드 수 있습니다.

<input type="text" id="search" autocomplete="off"> 

이제 사용자가 텍스트 영역에 입력하는 내용을 들어야합니다. 이를 위해 jquery live() 및 keyup 이벤트를 사용합니다.모든 키 - 업에는 PHP 스크립트를 실행할 jquery 함수 "search"가 있습니다.

이렇게 html이 있다고 가정 해 보겠습니다. 입력 필드와 결과를 표시하는 목록이 있습니다.

<div class="icon"></div> 
<input type="text" id="search" autocomplete="off"> 
<ul id="results"></ul> 

우리는 입력 필드에 KeyUp 이벤트를들을 것이고, 검색() 함수를 호출합니다 비어 있지 않은 경우 JQuery와 스크립트가 있습니다. search() 함수는 PHP 스크립트를 실행하고 AJAX를 사용하여 같은 페이지에 결과를 표시합니다.

다음은 JQuery입니다.

$(document).ready(function() { 

    // Icon Click Focus 
    $('div.icon').click(function(){ 
     $('input#search').focus(); 
    }); 

    //Listen for the event 
     $("input#search").live("keyup", function(e) { 
     // Set Timeout 
     clearTimeout($.data(this, 'timer')); 

     // Set Search String 
     var search_string = $(this).val(); 

     // Do Search 
     if (search_string == '') { 
      $("ul#results").fadeOut(); 
      $('h4#results-text').fadeOut(); 
     }else{ 
      $("ul#results").fadeIn(); 
      $('h4#results-text').fadeIn(); 
      $(this).data('timer', setTimeout(search, 100)); 
     }; 
    }); 


    // Live Search 
    // On Search Submit and Get Results 
    function search() { 
     var query_value = $('input#search').val(); 
     $('b#search-string').html(query_value); 
     if(query_value !== ''){ 
      $.ajax({ 
       type: "POST", 
       url: "search_st.php", 
       data: { query: query_value }, 
       cache: false, 
       success: function(html){ 
        $("ul#results").html(html); 

       } 
      }); 
     }return false;  
    } 



}); 

mysql 데이터베이스에서 쿼리를 실행하십시오. PHP는 AJAX를 사용하여 html에 들어갈 결과를 반환합니다. 결과는 html리스트에 저장됩니다.

'type'과 'desc'라는 두 개의 유사한 열 이름을 가진 두 개의 테이블 animals 및 bird가 포함 된 더미 데이터베이스가 있다고 가정합니다.

//search.php 
    // Credentials 
    $dbhost = "localhost"; 
    $dbname = "live"; 
    $dbuser = "root"; 
    $dbpass = ""; 

    // Connection 
    global $tutorial_db; 

    $tutorial_db = new mysqli(); 
    $tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname); 
    $tutorial_db->set_charset("utf8"); 

    // Check Connection 
    if ($tutorial_db->connect_errno) { 
     printf("Connect failed: %s\n", $tutorial_db->connect_error); 
     exit(); 

    $html = ''; 
    $html .= '<li class="result">'; 
    $html .= '<a target="_blank" href="urlString">'; 
    $html .= '<h3>nameString</h3>'; 
    $html .= '<h4>functionString</h4>'; 
    $html .= '</a>'; 
    $html .= '</li>'; 

    $search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']); 
$search_string = $tutorial_db->real_escape_string($search_string); 

// Check Length More Than One Character 
if (strlen($search_string) >= 1 && $search_string !== ' ') { 
    // Build Query 
    $query = "SELECT * 
    FROM animals 
    WHERE type LIKE '%".$search_string."%' 
    UNION ALL SELECT * 
    FROM birf 
    WHERE type LIKE '%".$search_string."%'" 
    ; 

    $result = $tutorial_db->query($query); 
     while($results = $result->fetch_array()) { 
      $result_array[] = $results; 
     } 

     // Check If We Have Results 
     if (isset($result_array)) { 
      foreach ($result_array as $result) { 

       // Format Output Strings And Hightlight Matches 
       $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']); 
       $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']); 
      $display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8'; 

       // Insert Name 
       $output = str_replace('nameString', $display_name, $html); 

       // Insert Description 
       $output = str_replace('functionString', $display_function, $output); 

       // Insert URL 
       $output = str_replace('urlString', $display_url, $output); 



       // Output 
       echo($output); 
      } 
     }else{ 

      // Format No Results Output 
      $output = str_replace('urlString', 'javascript:void(0);', $html); 
      $output = str_replace('nameString', '<b>No Results Found.</b>', $output); 
      $output = str_replace('functionString', 'Sorry :(', $output); 

      // Output 
      echo($output); 
     } 
    } 
관련 문제