如何将下拉更改事件链接到PHP函数

时间:2019-02-13 03:26:01

标签: javascript php html ajax mysqli

场景

对于下拉菜单,我具有以下HTML代码

<div class="form-group col-sm-2">
  <label>Machine</label><br>
  <select class="combobox form-control col-sm-2" name="machineNumber">
    <option>1</option>
    <option>2</option>
  </select><br>
  <label id="machineSer">Machine Serial Number: <?php echo $serialNumberRemarks; ?></label>
</div>

我需要的

当组合框发生变化时,我需要运行以下php函数,该函数运行查询并获取数据以显示ID为machineSer的标签所对应的项目。我的php功能如下

<?php
    function labelVal(){
        if(isset($_POST['machineNumber'])){
            $machineName = $_POST['machineNumber'];

            $query = "SELECT machineSerialRemarks FROM machinenames WHERE machineName = '$machineName'";
            $result = mysqli_query($conn, $query);
            $row = mysqli_fetch_array($result);
            $serialNumberRemarks = $row['machineSerialRemarks'];
            return $serialNumberRemarks;
        }
    }
?>

有人知道怎么做吗?我知道这与Javascript以及可能的Ajax有关。我浏览了一些Ajax,但不了解它是如何工作的。有没有不使用Javascript的方法?如果不可能,那么如何将这两个与Javascript和Ajax链接起来?

3 个答案:

答案 0 :(得分:1)

您应该将AJAX用于此任务。您可以使用jQuery ajax或普通JavaScript ajax。

我已经使用经过测试的香草JavaScript创建了一个完整的工作示例,并且效果很好。

这是我所做的更改:

  1. 我向HTML中的select元素添加了onchange侦听器,例如onchange="selectMachineNumber()"
  2. 我创建了一个名为selectMachineNumber的JavaScript函数,该函数将在每次更改选择菜单时执行。在此函数中,我们向一个名为machine_number_processing.php的php文件(包含您的php脚本)发出ajax请求。
  3. 我回显包含serialNumberRemarks变量的json编码响应。
  4. 然后,我将serialNumberRemarks插入到您的html中的span标签中(在您的标签内)。 span标签的ID为:machine-serial-number

index.html(或任何HTML页面名称)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
//declare a global xmlhttp variable 
var xmlhttp;

function createXHR(){
  //This function sets up the XMLHttpRequest
  try{
    return new XMLHttpRequest();
  }catch(e){
    //to support older browsers
    try{
      return new ActiveXObject("Microsoft.XMLHTTP");
    }catch(e){
      return new ActiveXObject("Msxml2.XMLHTTP");
    }
  }
}

function selectMachineNumber(selectElement){
   //this function will be called when there is a change in the machineNumber select menu
   //check the value selected in the console as follows:
   console.log(selectElement.value);
   var machineNumber = selectElement.value;
   //do ajax request
   xmlhttp = createXHR();
   xmlhttp.onreadystatechange = ajaxCallback; //name of our callback function here
   //Ive called the php file machine_number_processing.php but you can call it whatever you like.
   xmlhttp.open("POST", "machine_number_processing.php" ,true);
   xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   //send our variables with the request
   xmlhttp.send("machineNumber=" + machineNumber);
}

function ajaxCallback(){
   //this function will be executed once the ajax request is completed
   if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
      //The ajax request was successful.
      //we can now get the response text using xmlhttp.responseText. 
      //This will be whatever was echoed in the php file
      //we also need to parse this as JSON because we used json_encode on the PHP array we sent back 
      var data = JSON.parse(xmlhttp.responseText);
      console.log(data.machineNumber); 
      console.log(data.serialNumberRemarks);
      //insert the serialNumberRemarks to the span tag with id="machine-serial-number"
      document.getElementById("machine-serial-number").innerText = data.serialNumberRemarks;

   }
}


</script>
</head>
<body>
 <div class="form-group col-sm-2">
  <label>Machine</label><br>
  <select class="combobox form-control col-sm-2" name="machineNumber" id="machineNumber" onchange="selectMachineNumber(this)">
    <option>1</option>
    <option>2</option>
  </select><br>
  <label id="machineSer">Machine Serial Number: <span id="machine-serial-number"></span></label>
</div>
</body>
</html>

machine_number_processing.php

<?php
  if(isset($_POST['machineNumber'])){
    $machineName = $_POST['machineNumber'];

    $query = "SELECT machineSerialRemarks FROM machinenames WHERE machineName = '$machineName'";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_array($result);
    $serialNumberRemarks = $row['machineSerialRemarks'];

    //create a PHP array to store the data we will send back to the client side
    $responseData = array(); 
    //store the machineNumber that was submitted into a variable in order to test the ajax request
    //without performing the SQL query.
    $responseData['machineNumber'] = $_POST['machineNumber']; 

    //store the $serialNumberRemarks variable into our response array
    $responseData['serialNumberRemarks'] = $serialNumberRemarks;
    echo json_encode($responseData); //echo the response data back to the client
  }
?>

注意:正如您所知道的(正如人们在评论中所说的那样),您需要研究使您的SQL代码更安全,但是出于演示目的,我将您的PHP代码保持不变。

希望这会有所帮助:)

编辑

如果您只是想测试,那么ajax请求是否有效(无需执行SQL查询),则将php文件更改为以下内容

machine_number_processing.php

<?php
  if(isset($_POST['machineNumber'])){
    $machineName = $_POST['machineNumber'];
    //create a PHP array to store the data we will send back to the client side
    $responseData = array(); 
    //store the machineNumber that was submitted into a variable in order to test the ajax request
    //without performing the SQL query.
    $responseData['machineNumber'] = $_POST['machineNumber']; 

    echo json_encode($responseData); //echo the response data back to the client
  }
?>

然后在ajaxCallback函数中注释这两行

 console.log(data.serialNumberRemarks);
 document.getElementById("machine-serial-number").innerText = data.serialNumberRemarks;

您可以按照以下步骤检查在开发人员工具的“网络”标签下获得的响应:

response

编辑2-使PHP代码更安全

我想展示一个如何在项目中使用 PHP数据对象(PDO)扩展的示例。 这是用于访问PHP中的数据库的接口。

它具有准备好的语句,这有助于使处理更加安全(即有助于防止SQL注入)。

下面是一个有效的示例,说明如何将其合并到代码中(而不是使用mysqli)

您用于建立连接的文件如下所示:

connect.php

<?php
  //Define our connection variables. (really these credentials should be in a file stored in a private folder on the server but i'll them here for simplicity.)
  //set the character set for more security. (I will use utf8mb4. This is a good idea if you want to store emojis. YOu can just use utf8 though.
  define("HOSTDBNAME", "mysql:host=localhost;dbname=machine_app;charset=utf8mb4");     
  define("USER", "root");    
  define("PASSWORD", ""); 

  //initiate a PDO connection
  $pdoConnection = new PDO(HOSTDBNAME, USER, PASSWORD);
  $pdoConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  $pdoConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  //set the character set for more security. set it to utf8mb4 so we can store emojis. you can just use utf8 if you like.
  $pdoConnection->exec("SET CHARACTER SET utf8mb4");

?>

创建一个名为phpfunctions.php的文件以容纳getSerialNumberRemarks()函数,该函数对数据库进行查询以获取$serialNumberRemarks

phpfunctions.php

<?php
  function getSerialNumberRemarks($machineName, $pdoConnection){
    /*
     * This is a function to access the machinenames table using PDO with prepared statements and named parameters.
     * I have included extra comments (for learning purposes) with appropriate information taken
     * from the documentation here: http://php.net/manual/en/pdo.prepare.php
     */
    $serialNumberRemarks = ""; 
    try{
      //We create our $query with our named (:name) parameter markers 
      //These parameters will be substituted with real values when the statement is executed.
      //Use these parameters to bind any user-input, (N.B do not include the user-input directly in the query).    
      $query ="SELECT machineSerialRemarks FROM machinenames WHERE machineName = :machineName";

      //We now use the PDO::prepare() method on the query.
      //Note: calling PDO::prepare() and PDOStatement::execute() helps to prevent SQL injection attacks by eliminating the need 
      //to manually quote and escape the parameters.    
      $statement = $pdoConnection->prepare($query);

      //We now bind our user-input values.
      //If the user-input is an INT value then use PDO::PARAM_INT, if it is a string then use PDO::PARAM_STR.
      //$machineName will be an INT so bind the value as follows.
      $statement->bindValue(':machineName', $machineName, PDO::PARAM_INT); 
      $statement->execute();
      $statement->setFetchMode(PDO::FETCH_ASSOC);

      while($row = $statement->fetch()){
        $serialNumberRemarks = $row['machineSerialRemarks'];
      }
      return $serialNumberRemarks;
    }catch(PDOException $e){
      throw new Exception($e);
    }   
  }
?>

以下是AJAX请求要去的文件。我们需要包括connect.php文件和phpfunctions.php文件。

machine_number_processing.php

<?php
  require("connect.php"); //this file contains our PDO connection configuration
  require("phpfunctions.php"); //this file contains the getSerialNumberRemarks(); function

  if(isset($_POST['machineNumber'])){
    //store $_POST['machineNumber'] into a local variable
    $machineName = $_POST['machineNumber'];

    //checks should be done here to check the input is valid i.e it's a valid length, its valid encoding.
    //You should also filter the input. 
    //This can be done with PHP methods such as trim(), htmlspecialchars(), strip_tags(), stripslashes() 
    //and other methods depending on the type of input.
    //In this demonstration I will perform minimal sanitization of the input. 
    //Note: if its a string use FILTER_SANITIZE_STRING instead
    $machineName = filter_var($machineName, FILTER_SANITIZE_NUMBER_INT);

    //create a PHP array to store the data we will send back to the client side
    $responseData = array(); 

    //call the getSerialNumberRemarks() function and store the serialNumberRemarks returned into our response array
    $responseData['serialNumberRemarks'] = getSerialNumberRemarks($machineName, $pdoConnection);
    echo json_encode($responseData); //echo the response data back to the client
  }
?>

答案 1 :(得分:0)

您必须在此处使用jQuery / Ajax。如果您使用php,则必须先提交表单才能获取$_POST数据。这次,我认为您正在寻找元素中的event handling。让我们尝试一下:

在HTML上将代码更改为此:

 <div class="form-group col-sm-2">
  <label>Machine</label><br>
  <select class="combobox form-control col-sm-2" id="machineNumber" 
       name="machineNumber">
    <option>1</option>
    <option>2</option>
  </select><br>
  <label id="machineSer">Machine Serial Number: 
   </label>
</div>

示例脚本

     $("#machineNumber").change(function(){
            var id= $("#machineNumber option:selected").text();



           $.ajax({
                url:"call the function to your php",
                method:"POST",
                data:{
                    machinenum:id
                },
                dataType:"json",
                success:function(data){
               $('#machineSer').text("Machine Serial Number: "+data);
         }

      })
    });

您的PHP函数查询

<?php
function labelVal(){
    if(isset($_POST['machinenum'])){
        $machineName = $_POST['machinenum'];

        $query = "SELECT machineSerialRemarks FROM machinenames WHERE machineName = 
     '$machineName'";
        $result = mysqli_query($conn, $query);
        $row = mysqli_fetch_array($result);

      echo json_encode($row);
    }
  }
?>

希望这会有所帮助。

答案 2 :(得分:0)

应该看起来像这样(由于明显的原因而未被试用)。

请注意,我将name更改为id,以使其更易于访问。我也将您的请求更改为GET,因为a)根据GET合同,它仅从服务器获取信息,而不存储任何信息,并且b)因为它使fetch更加容易。下面的代码监视<select>的值何时更改,然后将请求发送到PHP后端。它可以像我的示例一样是一个单独的文件,或者您可以测试以查看请求是否具有machine参数以将其分流到您的函数中。当它显示其值时,我们返回到该JavaScript,并将其值放在响应的正文中,因此我们将使用text提取该值,最后将其插入HTML。请注意,您不能直接使用PHP标记来使用它,因为这是在页面加载之前发生的,并且以后无法在客户端重新解释它-我们需要使用普通的标记,并像我展示的那样更改DOM。

document.querySelector('#machineNumber').addEventListener('change', evt => {
  fetch("http://example.com/get_remarks.php?machineNumber=" + evt.target.value)
  .then(response => response.text())
  .then(text => document.querySelector('#machineSer').textContent = text);
})
<div class="form-group col-sm-2">
  <label>Machine</label><br>
  <select class="combobox form-control col-sm-2" name="machineNumber" id="machineNumber">
    <option>1</option>
    <option>2</option>
  </select><br>
  <label id="machineSer">Machine Serial Number: <span id="machineSer"></span></label>
</div>