Populate input fields with values when option is selected in php mysql - php

I have a form that i would like to submit details when an option is selected from the database.
The mysql database table :-
USERS contains fields like [email],[age],[name].
I want to be able to populate the other input fields values when one field is selected from the menu.
<form>
User
<select name="user" id="user">
<option>-- Select User --</option>
<option value="Mark">Mark</option>
<option value="Paul">Paul</option>
<option value="Hannah">Hannah</option>
</select>
<p>
Age
<input type="text" name="age" id="age">
</p>
<p>
Email
<input type="text" name="email" id="email">
</p>
</form>
How do i acheive this using jquery or javascript.

Please Try this,
on your HTML page:
write this to your html page,
<script>
$(document).ready(function(){
$('#user').on('change',function(){
var user = $(this).val();
$.ajax({
url : "getUser.php",
dataType: 'json',
type: 'POST',
async : false,
data : { user : user},
success : function(data) {
userData = json.parse(data);
$('#age').val(userData.age);
$('#email').val(userData.email);
}
});
});
});
</script>
in getUser.php:
getUser.php
<?php
$link = mysqli_connect("localhost", "user", "pass","mydb");
$user = $_REQUEST['user'];
$sql = mysqli_query($link, "SELECT age,email FROM userstable WHERE name = '".$user."' ");
$row = mysqli_fetch_array($sql);
json_encode($row);die;

Related

Updating form fields using AJAX and PHP

Problem: How can I update a form's select input values and text input fields based on a MySQL query after select input's onchange event is fired?
What I've tried:
I have tried to use AJAX with post and get data types, calling a php file that runs the query and echoes the results. Nothing displays. Any errors I have gotten along the way are usually small things that result in server 500 error. I have placed console.log statements in the function that runs the JQuery AJAX request. The change event was detected, the ajax success was called. I also tried using .load(), with GET and POST, no luck either. I have other features that implement AJAX, and I've tried modifying them to fit this scenario and have been unsuccessful.
I also tried to only use a select input that when changed would use AJAX request and .load function to display the other inputs which would be formatted on the php side and echoed to page with selected and values reflecting the db result.
What I want:
I would like a simple example of a form with a select input with three options, text type input, and a submit button. The form is a client backend form to send updates to the MySQL db. Each input represents a filed in the db. The idea is that when the user changes the select inputs selected value, a query is done that uses the selected value for only returning one result. Each field of that one records values in db should now be reflected in the form. First, tell me if this is the correct way to approach this problem, and if not show me how you would.
Example index.php:
<form action="editForm.php" method="POST" enctype="multipart/form-data">
<select id="contact_name" name="contact_name" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<input type="text" name="age" placeholder="Age" required>
<input type="text" name="race" placeholder="Select Race" required>
<select id="veteran_status" name="veteran_status" placeholder="Select Veteran Status" required>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
When on change event for #contact_name is fired I need to update the fields with the values the db has.
How would you implement this? Thanks in advance.
Update: as requested here is my JQuery code, but I know my example doesn't use the same names.
<script type="text/javascript">
$(document).ready(function(){
$('#currency_select').on('change', function (e) {
$.ajax({
type: 'post',
url: 'getCurrentValues.php',
data: {currency: 'EUR'},
success: function () {
console.log('ajax was submitted');
}
});
});
});
</script>
Here is my understanding of how to do this:
First, detect event and pass data via ajax for the query to retrieve record. This is in the document ready function to ensure DOM is ready.
$("#contact_name).on("change", function(e){
$.ajax({
type: 'post',
url: 'editForm.php',
data: {name: this.value},
success: function () {
console.log('ajax was submitted');
}
});
};
editForm.php:
include 'includes/db.php';
$name = $_POST['contact_name'];
$sql = "SELECT * FROM contacts;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$lastValues = array();
while($row = mysqli_fetch_assoc($result)) {
$age = $row['age'];
}
<input type="text" name="age" value="<?php echo $age; ?>">
<?php
}
?>
your index:
<select id="contact_name" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<form action="editForm.php" id="form" method="POST" enctype="multipart/form-data">
<select name="contact_name" id="contact_form" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<input type="text" id="age" name="age" placeholder="Age" required>
<input type="text" id="race" name="race" placeholder="Select Race" required>
<select id="veteran_status" name="veteran_status" placeholder="Select Veteran Status" required>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
$("#contact_name").on("change", function() {
var selected = $(this).val();
$("#form").load("formdata.php?contact="+selected); //normaly you do that with an id as value
OR
$.ajax({
type:"POST",
url:"formdata.php",
data: {user: selected},
dataType: "json",
success: function(response){
if(response.status == "success") {
$("#age").val(response.age);
$("#race").val(response.race);
$("#veteran_status").val(response.status);
} else {
alert("No data found for this user!");
}
});
});
and in your formdata.php file
//make your db-query
then either make the actual input fields which will be displayed if you use load
OR make something like if you use the ajax version
if($result) {
echo json_encode(array("status" => "success",age" => $result["age"], "race" => $result["race"], "status" => $result["status"]));
} else {
echo json_encode(array("status" => "failed"));
}
also you can delete the action, method and enctype in your form, as this will be set in the ajax function ;)
I would advice you to use the userid as the value in your select field, and you will also need to either also fill the contact_name IN the form OR make an hidden input field so that you can submit the form and know whos data this is..
just echo the $age variable in your editForm.php file and in the AJAX call success function alert the response. like so-
editForm.php
include 'includes/db.php';
$name = $_POST['contact_name'];
$sql = "SELECT * FROM contacts;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$lastValues = array();
while($row = mysqli_fetch_assoc($result)) {
echo $age = $row['age'];
}
}
?>
Ajax file
$("#contact_name).on("change", function(e){
$.ajax({
type: 'post',
url: 'editForm.php',
data: {name: this.value},
success: function (response) {
alert(response);
console.log(response);
}
});
};

Set selected value from database

I have the below code and I'm stuck finding solution for my problem. I want to select a value from a dropdown menu according on what the PHP result is.
<form>
<select name="filter" id="filter">
<option value="">Select</option>
<option value="AT_001">AT_001</option>
<option value="GG_001">GG_001</option>
</select><br><br>
<input type="text" name="name" id="name"><br><br>
<input type="text" name="reference" id="reference"><br><br>
<select name="gender" id="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</form>
$("#filter").change(function () {
var id = $(this).val();
$.ajax({
url : "getdata.php",
data : {
"id" : id
},
type : "POST",
dataType : "json",
success : function(data) {
console.log(data);
$("#name").val(data.fname);
$("#reference").val(data.reference);
$("#gender").attr("", data.gender); // ????? <--
}
});
});
$id = $_POST['id'];
$query = "SELECT fname, reference FROM tb_amity WHERE coc = '$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
echo json_encode($row);
}
You can use val() to set the selected option of a select element:
$("#gender").val(data.gender);
This is assuming that the data.gender value returned by your PHP is either 'Male' or 'Female'
First console what you are getting inside 'data.gender', if its value is present inside your options value then it works fine like:
$("#gender").val(data.gender);

On Dropdown Selection, how to fill complete form fields from Database

How to fill the complete form input fields from Database based on the value selected from the Dropdown
Example: In a Application, by selecting a client name it fills the complete form input fields with the details stored in the Database.
Sample Code:
<select name="client">
<option value="">-- Select Client Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
<input name="phone" type="text" value="">
<input name="email" type="text" value="">
<input name="city" type="text" value="">
<textarea name="address"></textarea>
All the about input fields need to be filled with values on client name selection.
EDIT:
I tried with AJAX but couldn't able get the particular variable from the file... below is my code:
<script>
$(document).ready(function() {
$('#client').change(function() {
alert();
var selected = $(this).find(':selected').html();
$.post('get_details.php', {'client': selected}, function(data) {
$('#result').html(data);
});
});
});
</script>
In the get_details.php file I am storing different values in different variables, but I didn't understand how to get them to individual variable to main page.
This is a just a basic jQuery example that calls itself (the top portion of the script is active when a $_POST is made), which I have named index.php as indicated in the url of the jQuery AJAX. You can use two separate pages to do this if you want. Just separate out the PHP from the HTML/Javascript and change the url: '/index.php':
<?php
// This is where you would do any database call
if(!empty($_POST)) {
// Send back a jSON array via echo
echo json_encode(array("phone"=>'123-12313',"email"=>'test#test.com','city'=>'Medicine Hat','address'=>'556 19th Street NE'));
// Exit probably not required if you
// separate out your code into two pages
exit;
}
?>
<form id="tester">
<select name="client" id="client">
<option value="">-- Select Client Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
<input name="phone" type="text" value="">
<input name="email" type="text" value="">
<input name="city" type="text" value="">
<textarea name="address"></textarea>
</form>
<!-- jQuery Library required, make sure the jQuery is latest -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: '/index.php',
type: 'post',
// This just sends the value of the dropdown
data: { client: $(this).val() },
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var Vals = JSON.parse(response);
// These are the inputs that will populate
$("input[name='phone']").val(Vals.phone);
$("input[name='email']").val(Vals.email);
$("input[name='city']").val(Vals.city);
$("textarea[name='address']").val(Vals.address);
}
});
});
});
</script>
When you made ajaxCall return data in json format like
json_encode(array("phone"=>'123-12313',"email"=>'test#test.com','city'=>'Medicine Hat','address'=>'556 19th Street NE'));
above shown
then parse it in jQuery and put the value in different selectors like
var Vals = JSON.parse(response);
// These are the inputs that will populate
$("input[name='phone']").val(Vals.phone);
above shown.

Dynamic Dependant Dropdown menu with ajax php mysql

I am attempting to make dynamic dropdown boxes a search tool to help narrow down display data from a mysql server. I am a decent php programmer but need help with the javascript and ajax.
The site currently consists of 3 pages: index_test.php, dropdown.php and dropdown2.php.
On index_test.php there are 4 dropdown menus that need to be populated with information. The first is populated with state names from a mysql table using php when the page loads. The second box is populated using .change() that references php code and and displays schools in the selected state from a mysql table.
The third box is supposed to then take the selected value from the second box and display the class names from the selected school to the user and that step is where the code is breaking. The php works when tested by submitting the form but I would like to be able to fill the last 2 boxes without a page refresh.
The format of the mysql tables are:
table schools: (school_id, schools, states)
table classes: (class_id, school_id, class_abrv, class_number)
Thank you for your help
The code for index_test.php:
<?php include_once("connect.php"); ?>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state = $("#state").val();
$.ajax({
type:"post",
url:"dropdown.php",
data:"state="+state,
success: function(data) {
$("#school").html(data);
}
});
});
$("#school").change(function(){
var state = $("#school").val();
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+school,
success: function(data) {
$("#classname").html(data);
}
});
});
});
</script>
</head>
<body>
<h1>Get Notes:</h1>
<br/>
<form action="dropdown2.php" method="post">
State: <select id="state" name="state">
<option>--Select State--</option>
<?php
$sql = "SELECT states FROM states";
$result = mysql_query($sql);
while ($output = mysql_fetch_array($result)) {
$state_name = $output['states'];
echo "<option value=\"$state_name\">$state_name</option>";
}
?>
</select>
<br/>
School: <select id="school" name="school">
<option>--Select School--</option>
</select>
<br/>
Class Name: <select id="classname" name="classname">
<option>--Select Class Name--</option>
</select>
<br/>
Class Number: <select id="classnumber" name="classnumber">
<option>Select Class Name</option>
</select>
<br/>
<input type="submit" value="Search" />
</form>
</body>
</html>
Dropdown.php:
<?php
include_once("connect.php");
$state=$_POST["state"];
$result = mysql_query("select schools FROM schools where states='$state' ");
while($school = mysql_fetch_array($result)){
echo"<option value=".$school['schools'].">".$school['schools']."</option>";
}
?>
Dropdown2.php
<?php
include_once("connect.php");
$school=$_POST['school'];
$result = mysql_query("SELECT school_id FROM schools WHERE schools='$school' ");
$school_id = mysql_fetch_array($result);
$id = $school_id['school_id'];
$classname = mysql_query("SELECT DISTINCT class_abrv FROM classes WHERE school_id='$id' ORDER BY class_abrv asc");
while($class = mysql_fetch_array($classname)){
echo"<option value=".$class['class_abrv'].">".$class['class_abrv']."</option>";
}
?>
in second ajax function you have assigned the school drop down box value to state variable but you pass the variable school to ajax post. So there is no school variable that is why you get error.
$("#school").change(function(){
var *state* = $("#school").val();
//above variable should be school.
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+*school*,
success: function(data) {
$("#classname").html(data);
}
});
});

jquery autocomplete and get value from mysql onchange

I need some help regarding making a form using PHP, MySQL, and jQuery.
Here is my HTML and PHP structure of form:
<form>
<label>Employee Name</label>
<input name="empid" type="text" id="search" <?php if (!empty($empid))echo "value='$empid'"; ?>>
<label>Leave Type</label>
<select name="leavetype" id="leavetype">
<option value="">--SELECT--</option>
<?php Loadlookup("id","leavetype","tbl_leavetypes",$leaveid,$d); ?>
</select>
<label>Leave Balance</label>
<input id="autopopulate" value="">
<input type="submit">
</form>
I am using autocomplete for finding the employee's name. How do I get both the name and ID of employee by autocomplete, and only show the employee's name in input, but the ID in some hidden field? Here is my autocomplete code in PHP:
require_once "config.php";
$q = strtolower($_GET["q"]);
if (!$q) return;
$sql = "select DISTINCT FullName as FullName from prmember where FullName LIKE '%$q%'";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
$cname = $rs['FullName'];
echo "$cname\n";
and this is the jQuery code for autocomplete:
<script type="text/javascript">
$().ready(function() {
$("#search").autocomplete("search/search.php", {
width: 260,
matchContains: true,
//mustMatch: true,
//minChars: 0,
//multiple: true,
//highlight: false,
//multipleSeparator: ",",
selectFirst: true,
});
});
</script>
After that, take a look at my HTML form code. when I change <select> in my form, then I want to auto populate the value of <input id="autopopulate" value=""> from the database.
It will be very helpful if you provide all code.
try the following and check this for more details
$('#leavetype').onchange(function(){
var lvType = $(this).val();
$.get("search.php?q="+lvType, function(data){
$('#autopopulate').val(data);
});
}
);

Categories