Populate the text fields automatically when id is provided

I am trying to populate table automatically from database when id is provided. I am using ajax but the code is not working . Please help me

//code: index.html

<html>
<head>
<script>
function showUser(str) {
  if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
  } else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("txtHint").innerHTML = this.responseText;
      }
    };
    xmlhttp.open("GET","getuser.php?q="+str,true);
    xmlhttp.send();
  }
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  </select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>

//code:getuserinfo.php

<html>
<head>
<style>
table {
  width: 100%;
  border-collapse: collapse;
}

table, td, th {
  border: 1px solid black;
  padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
  die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

what does that mean, where do you expect the error and what did you try to solve it?

1 Like

Like chorn saying the code is not working doesn’t help solve your coding problem.

I would put the javascript in a separate file and use an addEventListener instead.

I would get it working solely in php first then do the javascript as it will accomplish a few things. Like it will be more compliant if someone who disables javascript and in my opinion will be easier to do.

A few suggestions, I would use Fetch as it is now supported in most browsers with the exception of IE. I find it easier to work with. I suggest using PDO over mysqli as I find it easier to work with and gives you more options in my opinion.

Here’s an example of using fetch (it’s a trivia game that I have developed) ->

/* Handle General Errors in Fetch */
const handleErrors = function (response) {
    if (!response.ok) {
        throw (response.status + ' : ' + response.statusText);
    }
    return response.json();
};

/* Success function utilizing FETCH */
const quizUISuccess = (parsedData) => {
    mainGame.style.display = 'block';
    gameData = parsedData;
    //gameData = parsedData.sort(() => Math.random() - .5); // randomize questions:     
    totalQuestions = parseInt(gameData.length);
    createQuiz(gameData[gameIndex]);

};

/* If Database Table fails to load then answer a few hard coded Q&A */
const quizUIError = (error) => {
    console.log("Database Table did not load", error);
    console.log(failedLoad);
    gameData = [
        {
            id: 1,
            question: "What actor from the movie \"Dead Poets Society\" plays Dr. James Wilson on the TV show ",
            correct: 2,
            category: "movie",
            answers: ["Ethan Hawke", "Robert Sean Leonard", "James Waterston"]

        },
        {
            id: 55,
            question: "Who has won the most Oscars for Best Actress?",
            correct: 2,
            category: "movie",
            answers: ["Meryl Streep", "Katharine Hepburn", "Audrey Hepburn", "Jane Fonda"]
        },
        {
            id: 9,
            question: "Who played Jor-El in \"Superman (1978)\"?",
            correct: 4,
            category: "movie",
            answers: ["Glenn Ford", "Ned Beatty", "Christopher Reed", "Marlon Brando"]
        }
    ];

    /* Display HTML Game Display and create Quiz */
    mainGame.style.display = 'block';

    createQuiz(gameData[gameIndex]);
};

/* create FETCH request */
const createRequest = (url, succeed, fail) => {
    fetch(url)
            .then((response) => handleErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
};

/*
 * Start Game by Category
 */
const selectCat = function (category) {

    const requestUrl = `${quizUrl}category=${category}`;

    createRequest(requestUrl, quizUISuccess, quizUIError);

};
1 Like

Oh, if I had to guess why it isn’t working I would say your json isn’t parsed. It could be one of your problems.

Your thread title and your previous thread on this forum (where you were trying to dynamically build the select/option menu from the result of an sql query) implies you want to retrieve the data matching the selected id and populate text (form) fields with the values, so that you can edit/update the data. If you are not at the point where you can design, write, test, and debug just the html, php, and sql needed to do this, adding javascript/ajax on top of this will only make it harder for you to succeed.

Firstly, why aren’t you dynamically building the select/option menu from the result of an sql query? Did you just throwaway all your time and the forum member’s time that was put into that thread?

Next, the code needed for the current step should -

  1. Only execute the SELECT query if the post method edit/update form has NOT been submitted, since you only want to use the result from the SELECT query to initially populate the form field values, but you want to use the post method form data to repopulate the form field values after that point. The simple way of doing this is to define a common array variable to hold the data. Inside the post method form processing code, store a trimmed copy of the form data in this variable. After the end of the form processing code, if this variable is empty, you know that the form has never been submitted. You would use this condition to control if the code where the SELECT query is gets executed.
  2. Trim, then validate the get input before using it.
  3. Use a prepared query when supplying the external, unknown, dynamic value to the query when it gets executed.
  4. Do NOT use a loop to fetch the data from a query that is expected to match a single row. Just directly fetch the single row of data.
  5. Apply htmlentities() to any dynamic value when you output it onto a web page to help prevent cross site scripting.
  6. Output the fetched data as the form field value=’…’ attributes.

Once you get this step to work correctly, you are ready to submit the post method edit/update form and process that form data.

I want to auto populate a form when I input an id. The form should be autofilled with data from the database(MYSQL). I have implemented using the following javascript,javascript but code is not working . Please help

//code:index.php

<form method="post" action="">
  <select id="drop_mfd" onchange="showUser(this.value)">
  <option value="">Select mfd type:</option>
  <option >101</option>
  <option>102</option>
  <option >103</option>
  <option >104</option>
  </select></br>
  
  <label>mfd-type</label>
  <input type="text" id= "mfd_type_01"></br>
  <label>mfd-material</label>
  <input type="text" id= "mfd_mat_01"></br>
  <label>mfd-vendor</label>
  <input type="text" id= "mfd_vend_01"></br>
  <label>mfd-batch</label>
  <input type="text" id= "mfd_batch_01"></br>
  <label>mfd-date</label>
  <input type="text" id= "mfd_date_01"></br>
</form>
</div>

<script src="js/bootstrap.js"> </script>
<script src="js/jquery-3.2.1.min.js"> </script>
<script type="text/javascript">
function showUser(str) {
  if (str == "") {
    document.getElementById("mfd_type_01").value = "";
    document.getElementById("mfd_mat_01").value = "";
    document.getElementById("mfd_vend_01").value = "";
    document.getElementById("mfd_batch_01").value = "";
    document.getElementById("mfd_date_01").value = "";
    return;
  } 
else
{
    xmlhttp=new XMLHttpRequest();     
    xmlhttp.onreadystatechange = function() 
    {
      if (this.readyState == 4 && this.status == 200)
       {
       var data = JSON.parse(this.responseText);
      
          document.getElementById("mfd_type_01").value = data[0];
          document.getElementById("mfd_mat_01").value = data[1];
          document.getElementById("mfd_vend_01").value = data[2];
          document.getElementById("mfd_batch_01").value = data[3];
          document.getElementById("mfd_date_01").value = data[4];       
      }
    }
    xmlhttp.open("GET","getuser.php?drop_mfd="+str,true);
    xmlhttp.send();
 }
</script>

//getUser.php

<?php
include 'db_con.php';
$conn = OpenCon();
$drop_mfd = $_REQUEST['drop_mfd'];
$mfd_auto_query = mysqli_query($conn,"SELECT * FROM mfd WHERE ID = '".$drop_mfd."'"); 
$rowss = mysqli_fetch_array($mfd_auto_query);  
    $mtype = $rowss['MFD_Type'];
    $mmat = $rowss['MFD_Material'];
    $mvend = $rowss['MFD_Vendor'];
    $mbatch = $rowss['MFD_Batch'];
    $mdate = $rowss['MFD_Received_on'];
    $info = array("$mtype","$mmat","$mvend","$mbatch","$mdate");    
echo json_encode($info);
?>
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>

</body>
</html>

In addition to sticking with a single thread for this problem,

Sponsor our Newsletter | Privacy Policy | Terms of Service