I have a form which lists a number of stars (stellar objects) upon there is a <select>
control and two <inputs>
I am needing advice on populating the two inputs from the DB upon the change of the <select>
I am using PHP CSS HTML and wondering if I should go down the JS or Ajax route.
Here is the basic form page so far.
<?php
require( '../db_connect.php' );
include( '../inc/tvms_inc.php' );
session_start();
$starsq = "SELECT * FROM ast_stars WHERE constellation=5";
$starsr = mysqli_query( $conn, $starsq );
?>
<!doctype html>
<html data-bs-theme="dark" lang="en">
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
.center-screen {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 300px;
height: 150px;
border: 3px solid #c0c0c0;
text-align: center;
border-radius: 15px;
padding: 5px;
}
</style>
<link href="../css/bootstrap.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="center-screen">
<h4>Star Selector</h4>
<form action="process_add.php" method="post">
<select name="starnumber">STAR No :
<?php while($star=mysqli_fetch_assoc($starsr)) { ?>
<option value="<?php echo $star['omag']; ?>"><?php echo $star['omag']; ?></option>
<?php } ?>
</select>
<br>
<input name="xcoord" placeholder="X Coord"></input><br>
<input name="ycoord" placeholder="Y Coord"></input>
</form>
</div>
</body>
</html>
How would I achieve this?
I would need to do a mysqli query on changing the <select>
and populate the inputs from the results.
3
Answers
You can update form fields by calling a js function onchange=myfunction()
and add it to update form fields.
I would go the JS route. Since you’re populating all options as select options, I suppose there aren’t too many datasets, so there’s no need to make users wait for an ajax request to complete.
Here’s an example on how to achieve this:
You will have to change
$star['x']
and$star['y']
to whatever field names you are using. I was assumingx
andy
since you didn’t provide your db schema.You can separate the page that you get and fetch data from the database and then get them with js every time the page load or the select is change.
maybe this solution work for you