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.
Related
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);
}
});
};
I have a form and I want to set the values of the input fields on change of a form select. On change of the select ajax jquery runs and calls a PHP file with get method. But I don't know how to return the values from PHP (array or echo or any other way) and how to set them to the input values.
Using jQuery, this could be desired solution:
<form name="frm">
<input type="text" name="age" id="txtAge" />
<input type="text" name="country" id="txtCountry" />
<select name="name" id="selName">
<option value="Ceyhun Ganioglu">Ceyhun Ganioglu</option>
<option value="ABC">ABC</option>
<option value="CED">CED</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('select#selName').change(function(){
var name = $(this).val(); // selected option's value
$.getJSON("<URL_TO_PHP_SCRIPT>", { name: name }, function(data){
// on success, put returned value in textbox
// return data is in JSON (note, I am using `.getJSON` now)
$("#txtAge").val(data.age);
$("#txtCountry").val(data.country);
});
});
});
</script>
Your PHP Code could be:
<?php
echo json_encode(array('age' => 21, 'country' => 'US')); // you need to return on the basis of name, :)
?>
Read Ajax doc for jQuery $.getJSON here: http://api.jquery.com/jquery.getjson/
Other Ajax functions in jQuery: http://api.jquery.com/jquery.ajax/
I made an editable dropdown menu :
<html>
<body>
<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
<select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;" onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
<option></option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<input type="text" name="displayValue" placeholder="add/select a value" id="displayValue" style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;" onfocus="this.select()">
<input type="hidden" name="idValue" id="idValue">
</div>
</body>
</html>
I want to POST the value that was added, so as to include it in drop down for the next round.
I suggest you use jQuery for easy implementation. You can wrap them in a form and do the POSTing via jQuery Ajax then store that value somewhere for future use then append it to the next as the new option item.
POST via aJax
$(function() {
$('#form').on('submit', function(e) {
// do not reload the page
e.preventDefault();
// do the posting
var newValue = $('#displayValue').val();
$.post('http://MYURL.com/post.php', {
new_field: newValue
}, function(data) {
// success callback
$('#form > select').append('<option value="'+newValue+'">'+newValue+'</option>');
})
});
})
Basically, you post newValue to http://MYURL.com/post.php and handle that new data then the success callback will handle the inserting of the new value to your select.
the code is not tested, let me know if it did not work
Learn more about jquery.post() here and more about jquery here
I retrieve the value of a select box in this way which goes to populate a input field:
<script>
$(document).ready( function ()
{
$('#dropdown_selector').change(function()
{
var option = $(this).find('option:selected').val();
$('#showoption').val(option);
});
});
</script>
<select id="dropdown_selector">
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
<option value="Option3">Option3</option>
</select>
<label>Value</label>
<input type="text" name="name" id="showoption" disabled="disabled" />
</label>
But my problem is how to retrieve that value and use it directly in a PHP variable,instead of populating the input field(with id showoption).
Something similar as:
$variable=(var selected in select box)
Thanks for your help!!!
This jQuery code is triggered when an option is selected and then stores the value of the option into variable valu. After that it sends the variable to your php document via Ajax post.
$('select').change(function(){
var valu=$( "select option:selected" ).attr('value');
$.ajax({
type:"POST",
url:"yourphpscript.php",
data: {values:valu}
});
});
http://jsfiddle.net/joey6978/peq74/ :this fiddle shows the select choosing trigger.
In your php script you should have the post method with the name values to recieve your data.
$myvariable=$_POST['values'];
How can i display an alert message or alert box when getting the information(not submitting)
i have few form structures(text type) in my html when i enter the id in one of the form and press get button all the other forms will be filled based on the form submitted.
for the above i am using json and jquery
Ex:
Jquery
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='name']").val(json.name);
$("input[name='age']").val(json.age);
$("#institution").val(json.institution);
}, "json");
});
json:
$abc_output = array('title' => $row['title'],'name' => $row['name'],'age' => $row['age'], 'institution' => $row['institution']);
echo json_encode($abc_output);
now the problem is all the id's will not be having information so when the user enters some id with no information pop up or alert box need to be submitted saying no id.
How can i do that?
Note: as it is get info the result will be displayed on the same page, if its submit i could have echoed id not found in DB in the server side php(script_1.php) which is not the case here.
Html:
id: <input type="text" name="id"/>
<div id="hidden" style="display: none;">
<p>Title:<input type="text" name="title"/></p>
<p>name:<input type="text" name="rno"/></p>
<p>age:<input type="text" name="age"/></p>
Institution: <select id="institution" name="institution">
<option value="None">-- Select --</option>
<option value="ab">ab</option>
<option value="bc">bc</option>
</select>
</div>
<br/>
<input type="button" id="button1" value ="Get Info" onclick="document.getElementById('hidden').style.display = '';"/>
</form>
<div id="age"></div>
</body>
</html>
It may be helpful to set up an AJAX error handler, to handle things like session timeouts, json 'parseerror', etc.
$(document).ajaxError(function() {
alert( "Triggered ajaxError handler." );
});
This can help you to determine if the problem is with the success callback not being called.
You didn't post your opening <form> tag, but i'm assuming it has an id of 'myForm' (which you won't need).
I checked your javascript, and found a syntax error (a missing });). Try this:
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]').val() }, function(json) {
$("input[name='title']").val(json.title);
$("input[name='name']").val(json.name);
$("input[name='age']").val(json.age);
$("#institution").val(json.institution);
}, "json");
});
});
Notice I removed #myForm from the part that passes the values to php. The form itself does not have a value, the individual fields do.