简体   繁体   English

根据使用 ajax 在下拉列表中选择的内容填充我的输入字段

[英]Populating my input fields depending on what selected in dropdown using ajax

I want to populate my input fields which are texts depending on what I selected on my dropdown and I am using a procedural prepared statement for my back end.我想填充我的输入字段,这些字段是文本,具体取决于我在下拉列表中选择的内容,并且我正在为后端使用程序准备语句。 I can already retrieve the data from the the dropdown but I can't populate the fields whenever I click/select on dropdown data我已经可以从下拉列表中检索数据,但是每当我单击/选择下拉数据时,我都无法填充字段

Problem: I've already tried it but it doesn't change input fields whenever I try to change values in my dropdown menu.问题:我已经尝试过了,但是每当我尝试更改下拉菜单中的值时,它都不会更改输入字段。 I tried doing console in network and click my backend code and it does not give me an error.我尝试在网络中进行控制台并单击我的后端代码,但它没有给我一个错误。

myforms.php myforms.php

<form action="#" method="POST" enctype="multipart/form-data">
      <div class="form-group">
        <label for="LabelTitle">Research Title</label>
        <?php
        // this is where my <select> and <option> tag data retrieves
        include 'includes/includes_getOptionList.php';
        ?>
      </div>

      <div class="form-group">
        <label for="LabelTitle">Research UID</label>
        <input type="text" name="research_uid" class="form-control" id="research_uid" aria-describedby="emailHelp" placeholder="What is the title of the Research?" required="">
      </div>
      <div class="form-group">
        <label for="LabelTitle">Research Tags</label>
        <input type="text" name="researchTags" class="form-control" id="researchTags" placeholder="What is the type of this Research?" required="">
      </div>
      <div class="form-group">
        <label for="LabelTitle">Research Timeline</label>
        <input type="text" name="research_timeline" class="form-control" autocomplete="off" id="research_timeline" placeholder="What year was the research finished?" required="">
      </div>
      <div class="form-group">
        <label for="exampleFormControlTextarea1">Research Description</label>
        <textarea class="form-control" name="research_description" id="research_description" rows="8" required=""></textarea>
      </div>
      <div class="form-group">
        <input type="submit" name="submit" id="btn-add" class="btn btn-primary form-control" value="ADD">
      </div>
    </form>

<!-- my js function -->
  <script src="js/getdetails.js"></script>

getdetails.js获取详细信息.js

$(function(){
    $('#research_title').on('change',function(){
        $.ajax({
            url: "includes/includes_getDetails.php",
            type: 'POST',
            data: {
                research_title: $('#research_title').val()
            },
            success: function(data){
                researchData = JSON.parse(data);
                $('#research_uid').val(researchData.research_uid);
                $('#researchTags').val(researchData.researchTags);
                $('#research_timeline').val(researchData.research_timeline);
                $('#research_description').val(researchData.research_description);
            },
        });
    });
});

includes_getDetails.php包括_getDetails.php

<?php
// check connection
if(isset($_POST)){
    include 'connection_operation.php';

$research_title = $_POST["research_title"];
$sqlStatement = "SELECT research_uid, researchTags, research_timeline, research_description FROM tbl_topicresearch WHERE research_title = ?;";
$stmt = mysqli_stmt_init($conn);

if (!mysqli_stmt_prepare($stmt, $sqlStatement)) {
    echo "SQL Statement" . mysqli_stmt_error($stmt);
} else {
    mysqli_stmt_bind_param($stmt, "s", $research_title);
    mysqli_stmt_execute($stmt);
    $data = array();
    $getResult = mysqli_stmt_get_result($stmt);
    while ($row = mysqli_fetch_array($getResult, MYSQLI_ASSOC)) {
        $data[] = $row;
    }
    exit(json_encode($data));
}
}

?>

Edit: Added reference // I hope this added information will help.编辑:添加参考//我希望这个添加的信息会有所帮助。

This is my database.这是我的数据库。 在此处输入图像描述

This is the response这是回应在此处输入图像描述

You have set dataType: 'json' in your AJAX function and then, in the callback, call JSON.parse .您已在 AJAX function 中设置dataType: 'json' ,然后在回调中调用JSON.parse You do not need to set the dataType - in fact leaving that in will likely cause an error as jQuery automagically processes the JSON data.您不需要设置dataType - 事实上,将其保留可能会导致错误,因为 jQuery 会自动处理 JSON 数据。

Consider the following demo - made with static values as the select menu is unknown and no way to test your db/sql.考虑以下演示 - 使用 static 值制作,因为select菜单未知且无法测试您的 db/sql。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        $_POST['date']=date(DATE_ATOM);
        $_POST['foo']='bar';
        
        $_POST['research_uid']=uniqid();
        $_POST['researchTags']='a,b,c,d,e,f,g,h';
        $_POST['research_timeline']='first thing in the morning and last thing at night';
        $_POST['research_description']='random nonsense in the form of  adescription...';
        
        
        
        
        exit(json_encode($_POST));
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <script src='//code.jquery.com/jquery-latest.js'></script>
    </head>
    <body>
        <form action="#" method="POST" enctype="multipart/form-data">
              <div class="form-group">
                <label for="LabelTitle">Research Title</label>
                
                
                <?php
                // this is where my <select> and <option> tag data retrieves
                //include 'includes/includes_getOptionList.php';
                ?>
                
                
                <select id='research_title' name='research_title'>
                    <option value=1>One
                    <option value=2>Two
                    <option value=3>Three
                </select>
                
                
                
                
              </div>

              <div class="form-group">
                <label for="LabelTitle">Research UID</label>
                <input type="text" name="research_uid" class="form-control" id="research_uid" aria-describedby="emailHelp" placeholder="What is the title of the Research?" required="">
              </div>
              <div class="form-group">
                <label for="LabelTitle">Research Tags</label>
                <input type="text" name="researchTags" class="form-control" id="researchTags" placeholder="What is the type of this Research?" required="">
              </div>
              <div class="form-group">
                <label for="LabelTitle">Research Timeline</label>
                <input type="text" name="research_timeline" class="form-control" autocomplete="off" id="research_timeline" placeholder="What year was the research finished?" required="">
              </div>
              <div class="form-group">
                <label for="exampleFormControlTextarea1">Research Description</label>
                <textarea class="form-control" name="research_description" id="research_description" rows="8" required=""></textarea>
              </div>
              <div class="form-group">
                <input type="submit" name="submit" id="btn-add" class="btn btn-primary form-control" value="ADD">
              </div>
        </form>
        <script>
            $(function(){
                $('#research_title').on('change',function(e){
                    $.ajax({
                        url: location.href, //"includes/includes_getDetails.php"

                        type: 'POST',
                        data: {
                            research_title: $('#research_title').val()
                        },
                        success: function(data){
                            researchData = JSON.parse(data);
                            
                            $('#research_uid').val(researchData.research_uid);
                            $('#researchTags').val(researchData.researchTags);
                            $('#research_timeline').val(researchData.research_timeline);
                            $('#research_description').val(researchData.research_description);
                        }
                    });
                });
            });
        </script>
    </body>
</html>

删除 dataType:'json' 时的示例输出

When dataType:'json'dataType:'json'

dataType-json 导致的错误

Looking at the response in the newly added screenshot it shows a simple boolean true rather than any structured data.查看新添加的屏幕截图中的响应,它显示了一个简单的 boolean true而不是任何结构化数据。

include 'connection_operation.php';

$title = $_REQUEST['title'];

$sql = 'SELECT 
            research_uid, 
            researchTags, 
            research_timeline, 
            research_description 
        FROM tbl_topicresearch 
            WHERE title = ?;';

$stmt=$conn->prepare($sql);
$stmt->bind_param('s',$title);
$stmt->execute();
$stmt->bind_result( $research_uid, $researchTags, $research_timeline, $research_description );

$data=array();
while($stmt->fetch())$data[]=array(
    'research_uid'          =>  $research_uid, 
    'researchTags'          =>  $researchTags, 
    'research_timeline'     =>  $research_timeline, 
    'research_description'  =>  $research_description
);

$stmt->free_result();
$stmt->close();

header('Content-Type: application/json');
exit(json_encode($data));

or, with the procedural style:或者,使用procedural样式:

$data=array();
$getResult = mysqli_stmt_get_result($stmt);
while( $row=mysqli_fetch_array( $getResult, MYSQLI_ASSOC ) ){
    $data[]=$row;
}
exit(json_encode($data));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM