populate text boxes depend on drop-down selection in php - javascript

I research in google and stack overflow for this answer there are lot of answer but i cannot able to get what i want.
I have two drop down menus and three text boxes.
PHP Code :
<select onchange="FirstDropDownClick()"> </select>
script code :
<script type="text/javascript">
function FirstDropDownClick() {
var selectDwn = document.getElementById("ID_dwn");
var selectedValue = selectDwn.options[selectBox.selectedIndex].value;
}
In "FirstDropDownClick()" i want the codes for the following :
1.select data from database according to the selected value.
2.Fill the text boxes with that.
3.Fill second drop down according to value of first drop-down menu.
I need an example codes. Because am stuck , dont know how to do .
Thanks in Advance.

your html code
<select name="reg_number" id="reg_number">
<option value="1">Reg1</option>
<option value="2">Reg2</option>
<option value="3">Reg3</option>
</select>
<input type="text" name="first_name" id="first_name">
your jquery(make sure you include jquery file)
$(document).ready(function(){
$('#reg_number').change(function(){
var reg_number = $(this).val();
var data_String;
data_String = 'reg_number='+reg_number;
$.post('ajax_file.php',data_String,function(data){
var data= jQuery.parseJSON(data);
$('#first_name').val(data.first_name)
});
});
});
your php code (ajax_file.php)
<?php
$reg_number =$_POST['reg_number'];
//run your query here to fetch the result and store it in a variable $data
echo json_encode($data);
exit();`
?>

If you want to do it with ajax and php
HTML
<select name="select_number" id="select_number">
<option value="1">Number1</option>
<option value="2">Number2</option>
<option value="3">Number3</option>
</select>
<input type="text" name="number_value" id="number_value">
JQuery
$(document).ready(function(){
$('#select_number').change(function(){
var number_value = $(this).val();
$.ajax({
method: 'POST',
url: "test.php",
data: {
'number_value' : number_value
},
dataType:'json',
success: callback = function(data, textStatus, xhr)
{
$('#number_value').val(data.number_value);
}
});
});
});
php (test.php)
<?php
echo json_encode($_POST);
?>

why you need php for that you can do it only with jquery or javascript
HTML
<select name="select_number" id="select_number">
<option value="1">Number1</option>
<option value="2">Number2</option>
<option value="3">Number3</option>
</select>
<input type="text" name="number_value" id="number_value">
Jquery
$(document).ready(function(){
$('#select_number').change(function(){
var number_value = $(this).val();
$('#number_value').val(number_value);
});
});

Related

After ajax rerun php

I have an select menu that submits without reloading the page as follows:
<select id="option" name="option">
<option value="15">15/option>
<option value"30">30</option>
<option value"90">90</option>
</select>
It will submit to the current page as follows, without reloading the page
<script type="text/javascript">
$('#option').change(function(){
var option_val = $(this).val();
$.ajax({
type: 'post',
url: "$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];",
data: "option="+option_val,
success: function(data)
{
window.alert(data)
}
});
});
</script>
The result of a change in the option menu is an popup window with all the code of the page echoed back.
What i want to do on the page is use the $_POST['option'] that is submitted and recalculate a price for example
<body>
//some code and div's
<?php
if (isset($_POST['option'])) {
$option = $_POST['option'];
$price= $row_product['price'] + $option;
echo $price;
} ?>
</body>
The are several places where I would like to use the submitted option value
Any help welcome
Sorry if it is very obvious
The only way is making a PHP page that does the calculation
HTML/page1.php
<select id="option" name="option">
<option value="15">15</option>
<option value="30">30</option>
<option value="90">90</option>
</select>
<div id="dynamic">
<p>DEFAULT CONTENT</p>
</div>
HTML/page2.php
$option = 0;
if(isset($_GET["option"])){
$option = $_GET["option"];
}
//do calculations
echo "<my-html-stuff>lorem ipsum</my-html-stuff>";
JS
var dynamic = $("#dynamic");
$('#select').on("change", function() {
var selected = $(this).val();
dynamic.load("page2.php?option=" + selected, function() {
dynamic.html("<p>CONTENT OPTION "+selected+"</p>");
});
});
Fiddle ==> https://jsfiddle.net/tonysamperi/4dbwwn3g/
WITH JSON
page2.php
header('Content-Type: application/json');
$option = 0;
if(isset($_GET["option"])){
$option = $_GET["option"];
}
$response = ["result" => $option];
echo json_encode($response);
JS
$('#select').on("change", function() {
var selected = $(this).val();
$.get("page2.php?option=" + selected, function(response) {
//do stuff with data
console.debug("RESPONSE", response);
});
});

Load MySQL data without Refresh Webpage

I try to populate a select box based on the value of the another, by getting JSON data with jQuery from a PHP script that gets the data from a MySQL database.
This is my table :
I hope, if i select a different fruit from the first selection, it will change the available varieties in the second select.
According to my script, i'm not able to get corresponding available varieties into the second select, what wrong on my script.
<form>
Fruit:
<select name="name" id="fruitName">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
<option>Pear</option>
</select>
Variety:
<select name="variety" id="fruitVariety">
</select>
</form>
<script>
function populate() {
$.getJSON('varities.php', {fruitName:$('#fruitName').val()}, function(data) {
var select = $('#fruitVariety');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['variety']);
});
});
}
$(document).ready(function() {
populate();
$('#fruitName').change(function() {
populate();
});
});
</script>
and this is my varities.php script
$result = array();
$fruitName = $_GET['fruitName'];
$res=mysql_query("SELECT variety FROM fruit WHERE name = '$fruitName' ORDER BY variety");
while ($row=mysql_fetch_array($res)){
array_push($result, array('variety'=>$row['variety']));
}
echo json_encode(array('result'=>$result));
Please any suggestions?
Try the following function
function populate() {
$.getJSON('varities.php', {fruitName:$('#fruitName').val()}, function(data) {
var select = $('#fruitVariety');
var options = select.empty();//empty the select box
$.each(data.result, function(index, array) {//don't forget you have a result array
select.append('<option value="'+array.variety+'">'+array.variety+'</option>');//append the option elements
});
});
}
Make 2 separate tables,one for the fruits and another for the variety. Id of tbl_fruits will be a foreign key in tbl_variety.
1)First get all fruits and store the results in $fruits.
Therefore, first select will be like:
<select name="name" id="fruitName">
<?php foreach($fruits as $fruit): ?>
<option value="<?=$fruit['id']?>"><?=$fruit['name']?></option>;
<?php endforeach; ?>
</select>
Then you can populate the 2nd dropdown using ajax:
<select name="variety" id="fruitVariety">
</select>
<script>
var id=$('#fruitName').val();
$.ajax({ // first call will get the list as per the initial value of the fruit list when the page loads
url:"get_variety.php",
method:"POST",
data:{initial:id},
dataType:"html",
success:function(data)
{
$('#fruitVariety').html(data);
}
});
$('#category').change(function(){
var id = $(this).val();
$.ajax({ // this will be triggered whenever you select a different value from the fruits list
url:"get-variety.php",
method:"POST",
data:{id:id},
dataType:"html",
success:function(data)
{
$('#fruitVariety').html(data);
}
});
</script>
And in get-variety.php:
Check if $_POST['initial'] or $_POST['id'] is set and fire query accordingly:
$initial=$_POST['initial'];
$results= After executing('SELECT * FROM tbl_variety WHERE fruit_id="'.$initial.'"');
foreach ($results as $result) {
echo '<option value="' . $result["id"] . '">'.$result["variety"].'</option>';
}
Similary, run the query for the other POST variable.

Append json data to HTML List box

HTML code is :
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
Js Code :
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
and Php Code is :
$option = $_POST['get_option'];
$data = array();
$prdqty = $db->execute("select product_name from master_purchase where product_code='$option' and delet='0'");
while ($tqty = $prdqty->fetch_assoc())
{
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
}
echo json_encode($data);
while we selecting first selectbox content, need to add some data to second select box from database, we almost done the things but the second select box didn't show any values ,please help us to resolve the above problem
I tried your code with some hard code value and it perfectly working fine:-
Html+Jquery (in single page with .html extension):-
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- added jquery library-->
<script type="text/javascript">
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
</script>
Php (with hard-coded value):-
<?php
$option = $_POST['get_option'];
$data = array();
$data['fritm'] = ''; // you need to define it as empty string first
for($i = 0;$i<10;$i++) // hard-code started
{
$data['fritm'] .= '<option value="'.$i.'">'.$i.'</option>'; // append each option to the string one-by-one and check `.=` also
}
echo json_encode($data);
Output:-
http://prntscr.com/auyn7i
http://prntscr.com/auymzf
http://prntscr.com/auynij
Note:- problem may be occuring because either you missed jquery library of concatenation inside loop or some other error in your php file.
You need to do two things:
1) concatenate results in while loop. You are re-assigning the array variable causing latest one to overwrite the old one.
This way, only old value will be appended.
Change
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
To
$data['fritm'] .= '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
2) Change
$('#freeitem').html(response.fritm);
To
$('#freeitem').append(response.fritm);
As you are just appending options to drop down, not changing its HTML.

Multiple dynamic drop down select menus not working - PHP MySQL Jquery

I am building a form that will have three related drop down menus. First one is store locations, second Equipment at this location, third is components at this location.
So when I pick a location the page sends an AJAX request to load the select values for the equipment at this location. And when I pick the equipment it should load the components that belong to that equipment.
The third drop down for components is what's not appearing.
So my first drop down goes like this off the main file with the divs where the drop downs are added via AJAX calls:
<div class="input-group">
<strong>Select A Store Location:</strong>
<select class="form-control selectDesk" name="Location_ID" id="Location_ID">
<option value=1>HT1</option>
<option value=2>HT2</option>
<option value=3>HT3</option>
<option value=4>HT4</option>
<option value=5>HT5</option>
<option value=6>HT6</option>
</select>
</div>
<div id="equipment">
</div>
<div id="component">
</div>
The second drop down is dynamic loaded off a different file and inserted in a div via Jquery and AJAX. This is the code to make that happen
<?php
include('DBConnect.php');
$locID = $_POST['loc_id'];
$equipSQL ="SELECT Equipment_ID, Equipment_Name FROM Equipment WHERE Location_ID = $locID";
$equipResult = $my_dbhandle->query($equipSQL);
$numResults = $equipResult->num_rows;
?>
<strong>Select Equipment:</strong>
<div class="input-group">
<select class="form-control" name="Equipment_ID" id="Equipment_ID" style="min-width: 375px;">
<option value="0">No Equipment Needed For This Task</option>
<?php
for ($i=0; $i < $numResults; $i++){ //this will loop through the results and print them in the drop down menu
$row = $equipResult->fetch_assoc(); //Parse result into rows
echo "<option value=" . $row['Equipment_ID'] . ">" . $row['Equipment_Name'] . "</option>\n";
}
?>
</select>
</div>
And my third drop down is also loaded off another file via Jquery and AJAX
<?php
include('DBConnect.php');
$equipID = $_POST['equip_id'];
$compSQL ="SELECT Component_ID, Component_Name FROM Components WHERE Equipment_ID = $equipID";
$compResult = $my_dbhandle->query($compSQL);
$numResults = $compResult->num_rows;
?>
<strong>Select Component:</strong>
<div class="input-group">
<select class="form-control" name="Component_ID" id="Component_ID" style="min-width: 375px;">
<option value="0">No Component Needed For This Task</option>
<?php
for ($i=0; $i < $numResults; $i++){ //this will loop through the results and print them in the drop down menu
$row = $compResult->fetch_assoc(); //Parse result into rows
echo "<option value=" . $row['Component_ID'] . ">" . $row['Component_Name'] . "</option>\n";
}
?>
</select>
</div>
The Jquery is as follows:
<script>
$("#Location_ID").change(function(){
var locID = "";
var locID = $('#Location_ID').val();
$.ajax({
type: 'post',
url: 'equipDropDownByLocRepeatingTask.php',
data: 'loc_id=' + locID,
success: function (r) {
$('#equipment').html(r);
}
});
}).change();
$("#Equipment_ID").change(function(){
var equipID = "";
var equipID = $('#Equipment_ID').val();
$.ajax({
type: 'post',
url: 'compDropDownByLocRepeatingTask.php',
data: 'equip_id=' + equipID,
success: function (r) {
$('#component').html(r);
}
});
}).change();
</script>
So again, the first AJAX request for the second equipment drop down is loaded just fine. But the third drop down for the component select is not.
Thank you in advance for your help!
Hi I have modified your code please use this.
If this will work then I will explain the script
<script>
$("#Location_ID").change(function(){
var locID = "";
var locID = $('#Location_ID').val();
$.ajax({
type: 'post',
url: 'equipDropDownByLocRepeatingTask.php',
data: 'loc_id=' + locID,
success: function (r) {
$('#equipment').html(r);
initSecond();
}
});
}).change();
function initSecond(){
$("#Equipment_ID").change(function(){
var equipID = "";
var equipID = $('#Equipment_ID').val();
$.ajax({
type: 'post',
url: 'compDropDownByLocRepeatingTask.php',
data: 'equip_id=' + equipID,
success: function (r) {
$('#component').html(r);
}
});
}).change();
}
</script>
Try to execute this javascript :
$("#Equipment_ID").change(function(){ ....
... after the first ajax call, like this:
success: function (r) {
$('#equipment').html(r);
$("#Equipment_ID").change(function(){
...
...
}
}
Also the third dropdown should be:
<select name="Component_ID" and id="Component_ID" ...

Updating div based on dropdown response without refreshing

I am trying to create a dropdown that will update text on a page without refreshing the page. The updated text will be supplied by a php function which is passed a value from the dropdown. Right now, my dropdown does nothing, but here is where I've managed to get:
webpage.php:
My dropdown. Populated by a database.
<form method='post'>
<select name="skill1_level" id="skill1_level" onchange="skill1ValueChange(this.value)">
// PHP to dynamically populate list from the DB
<?php foreach ($skill_levels as $key => $skill_levels_list): ?>
<option value=""><?= $skill_levels_list->skill_level ?></option>
<?php endforeach ?>
</select>
</form>
My div. Currently just loading a default string. Need to figure out how to make this change when the dropdown is submitted. Not sure how to use AJAX here.
<div class="panel-body" id="skill1_text">
<?php echoSkill($hero->skill1_desc, $placeholders, $id_hero, 1, 1, $dbh); ?>
</div>
functions.js. Javascript to be called when dropdown is submitted. Calls PHP function.
function skill1ValueChange(skill_level) {
$.ajax({
url: 'functions.php',
type: 'POST',
data: {option : skill_level},
success: echoSkill($hero->skill1_desc, $placeholders, $id_hero, 1, skill_level, $dbh) {
console.log("Data sent for skill1.");
}
});
functions.php. does some stuff to my data based on the dropdown value, then echos the resulting string.
function echoSkill ($skill_desc, $placeholders, $id_hero, $skill_num, $skill_level, $dbh) {
$skill_values = fetchSkillValues($id_hero, $skill_num, $skill_level, $dbh);
$skill_values = array($skill_values[0]->skill_x, $skill_values[0]->skill_y, $skill_values[0]->skill_z, $skill_values[0]->skill_a);
$skill_desc = str_replace($placeholders, $skill_values, $skill_desc);
echo $skill_desc;
}
Any help and explanation you can provide would be greatly appreciated!
Probably the easiest for you would be to return HTML from your functions.php (actually, you should probably have it reference a different page that includes the functions.php page and echos the echoSkill() function) file:
Page with dropdown:
<!-- I assume you already have the libraries...-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<form method='post'>
<!--You can just add the change in the jQuery instead of inline js -->
<select name="skill1_level" id="skill1_level">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
</select>
<!-- This is where your empty div will fill with the php content -->
<div class="panel-body" id="skill1_text"></div>
</form>
<script>
// Select by the <select> named "skill1_level"
// When changed...
$("select[name='skill1_level']").change(function() {
// Assign the selection's value
var OptionVal = $(this).val();
$.ajax({
url: 'functions.php',
type: 'post',
data: { option: OptionVal },
// You need a success function here
success: function(response) {
// This will print out the response from your php page
// to the div on this page called "skill1_text"
$("#skill1_text").html(response);
}
});
});
</script>
functions.php
<?php
//code here to return just the text or whatever
// You should actually have the ajax call a page that has the "echoSkill()"
// function on it rather than the function page itself
echo 'Response to ajax page.';
echoSkill($blah,$blah2,$blah3,$blah4,$blah5,$blah6);
print_r($_POST);
?>

Categories