2016-11-25 35 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