Skip to content
Advertisement

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

<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

$(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

<?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. enter image description here

This is the response enter image description here

Advertisement

Answer

You have set dataType: 'json' in your AJAX function and then, in the callback, call 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.

Consider the following demo – made with static values as the select menu is unknown and no way to test your 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>

Example output when dataType:'json' is removed

When dataType:'json'

Error caused by dataType-json

Looking at the response in the newly added screenshot it shows a simple boolean true rather than any structured data.

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:

$data=array();
$getResult = mysqli_stmt_get_result($stmt);
while( $row=mysqli_fetch_array( $getResult, MYSQLI_ASSOC ) ){
    $data[]=$row;
}
exit(json_encode($data));
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement