如何使用AJAX,PHP和MYSQL在选择项目时在文本框中填充数据

How to populate data in text boxes on selection of an item using AJAX ,PHP and MYSQL

提问人:Coderstack 提问时间:9/3/2023 更新时间:9/5/2023 访问量:67

问:

我有一个表单,当用户选择一个地点时,我需要在文本框中获取数据。如果用户选择一个地点,则以下名称和金额将出现在以下文本框中。我已经做了以下工作,但它不起作用。谁能帮我解决这个问题?

我尝试了以下方法:

[HTML全文]

<div>
    <label for="" class="">Place</label>
    <select  name="place" id="place"  onchange="myplace();">
        <option value="">--Option from db--</option>
    </select>       
</div>

<div>
    <label for="" class="">Name</label>
    <input type="text"  name="myname" id="myname" value="<?php //if there is data in databas then it is shown here...otherwise the value will change according to the above selection?>" >  
</div>

<div>
    <label for="" class="">Amount</label>
    <input type="text"  name="myamnt" id="myamnt" value="<?php //if there is data in databas then it is shown here...otherwise the value will change according to the above selection?>" >  
</div>

MySQL数据库

if(!empty($_POST["myinitplace"]))
{
        
$sql = "SELECT * FROM all_data , my_place  WHERE all_data.place=my_place.place and all_data.place = ?";
$stmt = $conn->prepare($sql); 
$stmt->bind_param("s", $_POST["myinitplace"]);
$stmt->execute();
$result = $stmt->get_result(); 
while($rows = $result->fetch_assoc())   
{   
 $data['name']=$rows['name'] ;
 $data['myacc']=$rows['amount'] ;
                
}
echo json_encode($data);
                        
    }

阿贾克斯

function myplace() 
{
        
    var a = document.getElementById("place").value;
    //alert(a);
    $.ajax({
        type : "POST",
        data : {
            myinitplace : a 
        },
        dataType :  "JSON",
        success : function(data){
         document.getElementById("myname").value = data.name;
         document.getElementById("myamnt").value = data.myacc;
        }
    })  
}
php mysql ajax fetch

评论

0赞 Booboo 9/3/2023
你的错误是什么?您的 AJAX 是否发布到正确的 URL?您尚未指定 URL,因此它将回发到创建所显示 HTML 的原始 URL。请参阅如何创建最小的可重现示例。此外,您的 SELECT 语句使用旧语法。使用显式 JOIN 语法,或者 。"SELECT * FROM all_data INNER JOIN my_place WHERE ll_data.place=my_place.place and all_data.place = ?""SELECT * FROM all_data INNER JOIN my_place ON all_data.place=my_place.place and all_data.place = ?"

答:

1赞 manju nath 9/3/2023 #1
<?php
//your Database Connection//
require_once "database_conn.php";
//Option for page view //
$opt = (isset($_REQUEST['opt']))?$_REQUEST['opt']:"form";
if($opt=="form" or $opt=="")
{
?>

    <script src="jquery.js" type="text/javascript"></script>
    <script>
    function myplace() 
    {
            
        var a = document.getElementById("place").value;
        $('.ajax').html('Getting Data Fom database');
        $.post('http://localhost/test/test2.php?opt=code',{'place':a},function(d){
            $('.ajax').html(d);
            jsdata =JSON.parse(d);
            dataname = jsdata.name;
            dataamount = jsdata.amount;
            $('#myname').val(dataname);
            $('#myamnt').val(dataamount);
        });
        
    }
    </script>
            
    <div>
        <label for="" class="">Place</label>
        <select  name="place" id="place"  onchange="myplace();">
            <option value="">--Option from db--</option>
            <?php
                $getplaces_query="select * from my_place order by place";
                $getplaces_query_connect=mysqli_query($con,$getplaces_query) or die(mysqli_error($con));
                while($places_data = mysqli_fetch_array($getplaces_query_connect))
                {
                    ?><option value="<?=$places_data['place'];?>"><?=$places_data['place'];?></option><?php
                }
            ?>
        </select>       
    </div>
    <h4 class="ajax"></h4>
    <div>
        <label for="" class="">Name</label>
        <input type="text"  name="myname" id="myname" value="<?php //if there is data in databas then it is shown here...otherwise the value will change according to the above selection?>" >  
    </div>
    
    <div>
        <label for="" class="">Amount</label>
        <input type="text"  name="myamnt" id="myamnt" value="<?php //if there is data in databas then it is shown here...otherwise the value will change according to the above selection?>" >  
    </div>  
<?php
}
?>
<?php
if($opt=="code")
{
    $place = (isset($_POST['place']))?$_POST['place']:"";
    $getplaces_query="select place,name,amount from all_data where place = '".$place."'";
    $getplaces_query_connect=mysqli_query($con,$getplaces_query) or die(mysqli_error($con));
    $final_data=array();
    $places_data = mysqli_fetch_array($getplaces_query_connect);
    echo json_encode($places_data);
}
?>
0赞 Ken Lee 9/3/2023 #2

首先,我假设您已经在以下行中使用有效数据填充了选择块:

 <option value="">--Option from db--</option>

<option value="Place1">Place1</option>
<option value="Place2">Place2</option>

在这种情况下,您需要稍微修改您的 HTML 代码,以便它显式调用 PHP 脚本(通过指定 url),因此在 ajax 块中添加以下行:

 url: "xxxx.php",

假设 PHP 脚本的名称是 ,那么 HTML 将是:testSO3Sept2023.php

<script
  src="https://code.jquery.com/jquery-3.7.1.js"
  integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4="
  crossorigin="anonymous"></script>

<div>
    <label for="" class="">Place</label>
    <select  name="place" id="place"  onchange="javascript:myplace();">
        <option value="">Please select</option>
        <option value="Place1">Place1</option>
        <option value="Place2">Place2</option>

    </select>       
</div>

<div>
    <label for="" class="">Name</label>
    <input type="text"  name="myname" id="myname" value="" >  
</div>

<div>
    <label for="" class="">Amount</label>
    <input type="text"  name="myamnt" id="myamnt" value="" >  
</div>

<script>
function myplace() 
{
        
    var a = document.getElementById("place").value;
    //alert(a);
    $.ajax({
        type : "POST",
        data : {
            myinitplace : a 
        },
        url: "testSO3Sept2023.php",
        dataType :  "JSON",
        success : function(data){
         document.getElementById("myname").value = data.name;
         document.getElementById("myamnt").value = data.myacc;
        }
    })  
}

</script>

PHP 脚本 (testSO3Sept2023.php) (这是一个简单的 PHP,只是为了演示通过 AJAX 传递数据,在现实生活中请连接数据库)

<?php
if($_POST["myinitplace"]=="Place1"){
 $data['name']="New York" ;
 $data['myacc']="100.1" ;
                }

if($_POST["myinitplace"]=="Place2"){
 $data['name']="Beijing" ;
 $data['myacc']="20.2" ;
                }

echo json_encode($data);

?>

您可以通过此沙盒查看结果

评论

0赞 Coderstack 9/5/2023
你能分享testSO3Sept2023.php脚本中的代码吗?
0赞 Ken Lee 9/5/2023
当然,请参阅上面略微修改的答案,包括PHP脚本。
0赞 Coderstack 9/5/2023
非常感谢你。但是当我尝试与数据库连接时,什么也没出现。即使没有错误。当我处理您的代码时,它会运行。当我尝试显示数据库中的字段数据时,文本框中没有任何内容。