2016-11-25 57 views
2

我想在我的表單中爲選定的值獲取鍵(主鍵),因此我可以將鍵添加到連接表中。我從下拉列表中將表單更改爲自動完成。但不要如何做jQuery的地圖。php/jQuery獲取選定值的主鍵

這是我自動完成

<?php 
if (isset($_POST['type']) && $_POST['type'] == 'faculty_id') { 

    $type = $_POST['type']; 
    $name = $_POST['name_startsWith']; 
    $nameID = $_POST['nameID']; 


    $query = "SELECT FirstName, LastName, FacultyId FROM Test.Faculty where UPPER(FirstName) LIKE '" . strtoupper($name) . "%'"; 
    $result = mysqli_query($con, $query); 
    $data = array(); 
    while ($row = mysqli_fetch_assoc($result)) { 
     $name = $row['FirstName'] . ' ' . $row['LastName']; 
     $nameID = $row['FacultyId']; 
     array_push($data, $name); 
    } 
    mysqli_close($con); 


    echo json_encode($data); 
    exit; 
} 
?> 

PHP這是形式和jQuery頁面

<form action="Form.php" method="post"> 
    <input type='text' id="faculty_id" placeholder="Instructor" name="faculty_id" value='' /> 

    <input type="submit" value="submit" name="submit" /> 
</form> 
<script type="text/javascript"> 

    $('#faculty_id').autocomplete({ 
     source: function (request, response) { 
      $.ajax({ 
       url: 'Form.php', 
       dataType: "json", 
       method: 'post', 
       data: { 
        name_startsWith: request.term, 
        nameID: request.term, 
        type: 'faculty_id' 
       }, 
       success: function (data) { 
        response($.map(data, function (item) { 
         console.log(item); 
         //var code = item.split("|"); 
         return { 
          label: item, 
          value: item, 
          data: item 
         } 
        })); 
       } 
      }); 
     }, 
     autoFocus: true, 
     minLength: 1, 

    }); 
</script> 

和PHP插入查詢

<?php 
if (isset($_POST)) { 
    $faculty_id = $_POST['faculty_id']; 
    try { 
     $stat = $db->prepare("Insert into ATCTest.Schedule 
         (Faculty) 
         VALUE (':faculty_id')"); 
     $stat->bindParam(":faculty_id", $faculty_id); 

     if ($stat->execute()) { 
      echo "<h5>Faculty-js: " . $faculty_id . "</h5>"; 
     } else { 
      echo "Problem!!!"; 
     } 
    } catch (PDOException $e) { 
     echo $e->getMessage(); 
    } 
} 

回答

1
  1. 保持一致。選擇PDOMySQLi。不是都。您的自動完成腳本使用MySQLi,但在插入腳本中使用PDO。挑一個並堅持下去。

我會使用PDO,因爲我發現它比MySQLi更容易使用。

  1. 使用適當的請求方法。如果您正在獲取某些內容,請使用GET而不是POST。如果您正在添加或更新,請使用POST。

讓我們來重寫你的自動完成腳本使用PDO:

if (isset($_GET['type']) && $_GET['type'] == 'faculty_id') { 
     // this will hold your response that gets sent back 
     $data = null; 
     $name = trim($_GET['name']); 

     try { 
      // because you are passed untrusted data, use prepared statement 
      $sth = $db->prepare(" 
       SELECT FirstName, LastName, FacultyId 
       FROM Test.Faculty 
       WHERE UPPER(FirstName) LIKE UPPER(?) 
      "); 
      $sth->execute(array($name . '%')); 
      // set the results (array of objects) as your JSON response 
      $data['faculties'] = $sth->fetchAll(PDO::FETCH_OBJ); 
     } catch(PDOException $e){ 
      echo $e->getMessage(); 
     } 
     // send the results i.e. response 
     header('Content-Type: application/json'); 
     echo json_encode($data); 
     exit; 
    } 
  • 我以前從未使用過的自動完成插件,但我會在它需要一個裂縫基於我見過的其他答案。

    $('#faculty_id').autocomplete({ 
        source: function (request, response) { 
         // short syntax for .ajax() using GET method that expects a JSON response 
         $.getJSON('Form.php', { type: 'faculty_id', name: request.term }, function (data) { 
          // data.faculties (your AJAX script's response) should now be an array of objects 
          console.log(data.faculties); 
          response($.map(data.faculties, function (faculty) { 
           console.log(faculty); 
           return { 
            label: faculty.FirstName + ' ' + faculty.LastName, 
            value: faculty.FacultyId 
           } 
          })); 
         }); 
        }, 
        autoFocus: true, 
        minLength: 1, 
    }); 
    
  • 最後,當你插入

    // check if form was POSTed 
    if ($_SERVER['REQUEST_METHOD'] === 'POST') { 
        $faculty_id = $_POST['faculty_id']; 
        try { 
         // VALUES not VALUE 
         // don't wrap your placeholders with quotes in your prepared statement 
         // simplified 
         $sth = $db->prepare("INSERT INTO ATCTest.Schedule(Faculty) VALUES(?)"); 
         // simplified way to bind parameters 
         $sth->execute(array($faculty_id)); 
         // use rowCount() not execute() to determine if the operation was successful or not 
         if ($sth->rowCount()){ 
          echo "<h5>Faculty-js: $faculty_id</h5>"; 
         } else { 
          echo "Problem!!!"; 
         } 
        } catch (PDOException $e) { 
         echo $e->getMessage(); 
        } 
    } 
    
  • +0

    感謝您的回覆@Mikey,但自動完成不工作。它也不會給出任何錯誤。 – codelearner

    +0

    查看我上次編輯的錯字。 [打開你的PHP錯誤](http://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display)如果你還沒有這樣做。確定問題的確切位置:「它是JS還是PHP或兩者兼而有之?」通過打開瀏覽器的開發者工具(Chrome有一個漂亮的界面)開始JS:檢查控制檯日誌是否有任何輸出;檢查網絡選項卡(XHR)並查看鍵入數據時發送的請求和響應。做完所有這些之後,請澄清_autocomplete的含義是不是工作。 – Mikey

    +0

    它正在工作,但它在選擇標籤(名稱)後顯示值(facultyId)。和它的JS錯誤。我不知道關於打開錯誤php.ini,會看起來更多的JS自動完成。 – codelearner