首页 > 解决方案 > 如何通过 Ajax 将数据从 HTML 传递到 PHP 文件?

问题描述

我想知道,如何<select>通过 ajax 将元素从 html 传递到 PHP 文件。

这是我的index.php

<p>
<form action = "display.php" method="post" enctype="multipart/form-data">

Select: 

<select name="chosenOption" id="chosenOption"  style="width:100px"">
    <?php
    include 'dbConnection.php';
    $query = $db->query("SELECT id,name FROM products");
    while($row = $query->fetch_assoc())
    {
    echo'
    <option value="'.$row['id'].'">'.$row['name'].'
    </option>';
    }
    ?>
    </select>

Display : <input type="submit" name="display" value="Display">

</form>
</p>

display.php的,我有ajax方法的地方:

<script type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 
</script>
<script>
function refresh_div() {
        var chosenOption= $('#chosenOption').val();
        jQuery.ajax({
        url: 'products.php',
        type:'POST',
        data:{chosenOption:chosenOption},
        success:function(results) {
        jQuery(".result").html(results);
        }
    });
}
t = setInterval(refresh_div,1000);
</script>


<div class="result"></div>

而且products.php,我想在哪里传递选定的< select >元素:

<?php
include 'dbConnection.php';
$chosenOption = $_POST["chosenOption"];

// Display section

$query = $db->query("SELECT cost,description FROM products_info WHERE products_id=$chosenOption);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
echo "Actual cost and description: ".$row["cost"]. " ".$row["description"]. ; 
 }
 } else {
    echo "No data";
  }

?>

我希望选择的选项 fromindex.php将通过 ajax 传递给 products.php 并显示适当的消息。当前代码不起作用。任何的想法?

标签: phpjqueryhtmlajax

解决方案


不能引用$("#chosenOption")in display.php,因为页面已经重新加载。您需要使用$_POST['chosenOption'],因为它是由表单提交的。

<script type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 
</script>
<script>
function refresh_div() {
    var chosenOption= $('#chosenOption').val();
    jQuery.ajax({
        url: 'products.php',
        type:'POST',
        data:{chosenOption: <?php echo $_POST['chosenOption']; ?>},
        success:function(results) {
        jQuery(".result").html(results);
        }
    });
}
t = setInterval(refresh_div,1000);
</script>


<div class="result"></div>

推荐阅读