Dynamically update dropdown based on previous selection with PHP PDO - php

This has been answered before, however I'm asking again for two reasons: I can't find any resources that utilize PDO, and regardless of that, all of the ones I've found consist of code without any comments or explanations, which makes it hard to interpret and adapt them to my use case.
I need to be able to make a dropdown dynamically update itself based on the selection of the previous one, and if I change that selection, it should re-update itself without having to submit the form or reload the page.
I've updated the code with what I've learned and found so far, but it's still not working properly. Everything works up to the point where the second dropdown should begin loading values.
HTML:
<div class="form-group row">
<label class="col-sm-2 form-control-label" onchange="productorInfo(this.value);">Codigo Productor (*)</label>
<div class="col-sm-4">
<select name="vendedor_codigo">
<?php foreach ($dd_productor_result as $dd_productor_display) : ?>
<option value="<?= $dd_productor_display['vendedor_codigo']; ?>">
<?= $dd_productor_display['vendedor_codigo']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<label class="col-sm-2 form-control-label">Nombre (*)</label>
<div class="col-sm-4">
<select id="ajax-vendedor" name="vendedor_nombre">
<?php foreach ($ajax_productor_result as $dd_productor_display) : ?>
<option placeholder="Seleccione codigo" value="<?= $dd_productor_display['vendedor_nombre']; ?>">
<?= $dd_productor_display['vendedor_nombre']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
Ajax script:
function productorInfo(id) {
$.ajax({
type: "GET",
url: "/controller/produccion/db_ajax_update.php",
data: "mainid =" + id,
success: function (result) {
$("#ajax-vendedor").html(result);
}
});
};
First dropdown PHP code:
$dd_productor = "SELECT vendedor_codigo FROM lista_productores";
$productor_stmt = $pdo->prepare($dd_productor);
$productor_stmt->execute();
$dd_productor_result = $productor_stmt->fetchAll();
Second dropdown (ajax call):
if(isset($_GET['mainid'])){
productorInfo($_GET['mainid']);
$prod_value = productorInfo($_GET['mainid']);
}
$ajax_productor = "SELECT vendedor_nombre FROM lista_productores WHERE vendedor_codigo = {$prod_value}";
$productor_stmt = $pdo->prepare($ajax_productor);
$productor_stmt->execute();
$ajax_productor_result = $productor_stmt->fetchAll();

The onchange call should be on the select element not on the label
<label class="col-sm-2 form-control-label">Codigo Productor (*)</label>
<select name="vendedor_codigo onchange="productorInfo(this.value)">
But also it occurs to me you may not quite understand the process. Your ajax call won't be fired when the page loads so this bit:
<select id="ajax-vendedor" name="vendedor_nombre">
<?php foreach ($ajax_productor_result as $dd_productor_display) : ?>
<option placeholder="Seleccione codigo" value="<?= $dd_productor_display['vendedor_nombre']; ?>">
<?= $dd_productor_display['vendedor_nombre']; ?>
</option>
i would think is giving you undefined variable warnings (unless you are setting $ajax_productor_result initially in some way)
Responses from ajax are usually drawn in .js via success: function
(result) {
$("#ajax-vendedor").html(result);
}
from the looks of this though - unless there is more code that what has been posted, you are passing the .html() function an array or database rows so it's never going to display anything.
so you need to
1)draw a select with no options in it on pageload (or default options if you have them)
2)return a response that the success function can make use e.g. a json string which jquery can the parse
3)format the data in jquery into the <options> and then user the .html() function to update the select
4)if you want this to happen when the page initially loads then add in a document ready call to the productorInfo(id) function - this would be relevant if you are setting the initial select value in some way (so it may not be relevant to you)

Related

select option of select2 was missing after submit the update and how to set the selected value from database

I have several problems with select2. First, The select option of select2 is not display the value from database when I click edit button to show an edit modal.
Here's the edit modal:
here's the code:
<script>
// Edit
$('body').on('click', '.edit', function (event) {
event.preventDefault();
let id = $(this).attr('id');
$.get('/admin/diklat/diklats/' + id + '/edit', function (data) {
$('#code').val(data.data.code);
$('#name').val(data.data.name);
$('#lesson_hour').val(data.data.lesson_hour);
$('#department_id').val(data.data.department_id);
$('#schema_code').val(data.data.schema_code);
$('#committee').html('');
for (let index = 0; index < data.committee.length; index++) {
$('#committee').append(`<option selected value="${data.committee[index]}">${data.committee[index]}</option>`)
}
$('#id').val(data.data.id);
$('#start_date').val(data.data.start_date);
$('#end_date').val(data.data.end_date);
$('#location').val(data.data.location);
$('#regency_id').val(data.data.regency_id); // this is the part that cannot show its value
$('#modal-diklat').modal('show');
})
});
</script>
<div class="row">
<div class="col">
<div class="form-group">
<label class="form-label" for="regency_id">Kabupaten</label>
<select id="regency_id" name="regency_id" class="select2 form-control">
<option value=""></option>
#foreach ($regencys as $regency)
<option value="{{$regency->id}}">{{$regency->name}}</option>
#endforeach
</select>
</div>
</div>
</div>
Second problem is the select option of select2 is missing when I click the update button.
here:
And when the update process is done (and I want to add one more data without reload the page), it's still missing like the image shown above. But, when I reload the page,
it reappears like normal.
Anyone could help me with this issues, please? I've been looking for a solution but unfortunately I still can't solve it
Solved. For the first issue, just need to define something like
$('select').select2();
And for the second issue just need to add .trigger("change");
Example:
$('#regency_id').val(data.data.regency_id).trigger('change');
Note: OP provide an answer on question section.

Dynamicly populate field after getting value from dropdown

I have a form that uses a dropdown menu to select an option. After the option is selected I want to get a value form my DB to populate the next field with the correspondent value (in the scenario is to get the square footage of a rental property - but this value can be edited)
This is the field where i have the options:
<div>
<label class="control-label " for="local">Local</label>
<select class="select form-control" id="local" name="local" ><?php echo $lista_fraccoes;?></select>
</div>
after this i have the script to get the data:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#local').on('change', function(){
var .local = this.value;
$.ajax({
type: "POST",
url: "area_fraccao.php",
data:'local='+local,
success: function(result){
$("#area").value(result);
}
});
});
</script>
And after this i have the field that i want to populate:
<div class="form-group m-2 ">
<label class="control-label " for="area" type="value">Area</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fas fa-ruler-combined"></i>
</i>
</div>
<input class="form-control" id="area" name="area" placeholder="Em m2" type="value" value=""/>
</div>
In the area_fraccao.php file is where i get the correspondent value:
require_once 'config.php';
require_once 'functions.php';
$local = $_GET['local'];
$query_area = "SELECT * FROM TbFraccao WHERE PkFraccao=" . $local;
$result_area = mysqli_query($link, $query_area);
while ($row_area = mysqli_fetch_assoc($result_area)){
$area = $row_area['FraccaoArea'];
echo $area;
};
The solution I'm Using is presenting the following errors in web inspector
The code I'm using is updated matching the given suggestions.
Looking at your code, The code seems Ok. Please make sure that the query has no error by checking if running query was successful, check there is atleast one result and remove the semi-colon after while closing bracket.
if($result_area = mysqli_query($link, $query_area)){//the query is Ok
if(mysqli_num_rows($result_area)>0){//check there is atleast one result
while ($row_area = mysqli_fetch_assoc($result_area)){
$area = $row_area['FraccaoArea'];
echo $area;
}
}
}
else{//you have an error when writing your query
echo 'Wrong query';
}
if that does not help, the problem might be you did not sanitize the data during saving and there are characters from that data that interferes with the query. Show us how you did filtering before saving the data.
Set value of input elements using value method of jQuery
$("#area").value(result);
html() method is used to set innerHTML of elements

Ajax creating PHP variable from selectbox

So i'm trying to make it so when I select something from the first select box will create a PHP variable.
Say in the select box I select option 1, it will create a php variable like $number = 1;. or if I select option 5 it'll create a variable like $number = 5;.
I know this require's ajax, but I have minimal to no experience with this at all.
Code:
<form class="form-horizontal row" id="select-service">
<div class="form-group">
<label class="col-sm-4 control-label">Select Social Media</label>
<div class="col-sm-4">
<select class="form-control" name="category" id="category" onchange="func(this.value)">
<?php
$stmt = $pdo->prepare('SELECT * FROM categories');
$stmt->execute();
if($stmt->rowCount() > 0) {
echo'<option selected="true" style="display:none;">Select a social media</option>';
} else {
echo '<option selected="true" style="display:none;">No social medias are available</option>';
}
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Select Service</label>
<div class="col-sm-4">
<select class="form-control" id="service" onchange="quantity(this.value)">
<option selected="true" style="display:none;">Please select a category.</option>
</select>
</div>
</div>
<ul class="pager wizard">
<div class="pull-right">
<li class="next">
<button href="#" class="btn btn-info"><i>Next</i></button>
</li>
</div>
</ul>
You cannot alter PHP variables on runtime (at least not from the same document you are executing the AJAX script). This is because PHP and jQuery are executed on diferent levels:
PHP is server side processing and jQuery happens on the client side.
Yes. AJAX can be used to make PHP requests but it does not exactly can alter variables in real time.
AJAX is a client side solution for calling external php files. in these files you could do basically anything you can do with a php request:
Read data from server
Insert data to server
Update parameters
Etcetera.
What you could do, depending on what you need is desing your site so what you need could be done using an external php file.
You call myfile.php?number=1 using AJAX
And then in myfile.php
<?php
$number = $_GET["number"]; // this sets the $number var to 1
//process or do whatever you need with the number
echo $number;
?>
This echo call will not be displayed on sceen as it normally is but instead you fetch it to Javascript or jQuery and process whatever you need it for.
I recomend you read the W3 Schools guide on AJAX for JS because it contains examples and it is very well explained on what you can do and how tho acomplish it.

Show price from DB

The user goes change the nm_peca, will select tipo_preco and then find the price in MySQL database to complete the textbox vlr_peca.
What do I need to do to get the value of products?
<?php>
$query = mysql_query("SELECT id, nm_peca, vlr_original,
vlr_paralelo, fabricante
FROM peca
ORDER BY nm_peca");
<select id="nm_peca" name="nm_peca"
title="Selecione um status."
class="form-control" size="1">
<option value="">Status</option>
<option value="N/A">N/A</option>
<option value="S">S - Substituir</option>
</select>
</div>
</div>
<select id="tipo_preco" name="tipo_preco"
class="form-control" size="1">
<option value="">Tipo</option>
<option value="Peça Original">Original</option>
<option value="Peça Paralela">Paralela</option>
</select>
</div>
</div>
<div class="col-md-1">
<div class="input-group btn-group">
<input type="text" value="????????" name="vlr_peca"
class="form-control" readonly>
</div>
</div>
Well your code is a little confusing because what you really want is not clear to me, maybe it doesn't help that it's in a different language. What is the $query for? You are not using this in the code, so you'll need to do this to access it:
$rows = array();
while ($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
print '<pre>'. print_r($rows, true) . '</pre>';
Then you'll need to use an ajax request OR setup javascript vars on the front end to make changes. I'm just going to go ahead and use the latter since it's more illustrative.
So I would add the cdn of jQuery which is https://code.jquery.com/jquery-2.1.4.min.js to the top of your file in a tag like:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
Then you'll need to add an input id to that input tag like <input id="dynamic-variable" type="text" value="????????" name="vlr_peca"> and then use something like:
<script type="text/javascript">
$(document).ready(function() {
$('#tipo_preco').change(function() {
if ($(this).val() == 'Peça Original') {
$('#dynamic-variable').val('$5,000,000,000.00');
} else if ($(this).val() == 'Peça Paralela') {
$('#dynamic-variable').val('$300 billion trillion dollars');
} else {
$('#dynamic-variable').val('Bro. Choose one.');
}
});
});
</script>
I'm not going to program this whole thing for you since I don't know what kind of data you are getting from your DB, but this should be good enough to get you started. You need to be able to access the data in the mysql query, and you may just want to use the <?= $db_variable ?> or <?php echo $db_variable?> in your javascript where I have the amount variables. This should be good enough to get you started. Read up on php mysql_query and jQuery
AJAX
If you were to do this via AJAX, you would need a second page that accesses the database, you'd have to $_GET or $_POST variables and then print back the amount.
So your JavaScript would be something like this:
$.get('/the/page.php?tipo_preco=' + $('#tipo_preco').val(), function(response) {
if (response != '') {
$('#dynamic-variable').val(response);
}
});
And your second page would be something like this:
<?php
// code that sets up the database
// .... //
// now your code
$selected_value = $_GET['tipo_preco'];
$result = mysql_query("SELECT price FROM table WHERE column_val = '" . mysql_real_escape_string($selected_value) . "'");
$row = mysql_fetch_assoc($result); // assuming you're only fetching one row
print $row['price'];
?>
I would suggest you just go with the first suggestion, it's faster, less moving parts.

Ajax with bootstrap.TbSelect2 (Yii)

I have a Select whose contents are changed when another Select is changed.
On change ajax runs a function in my controller to do this:
$this->renderPartial("_townsselect", array('country'=>$country));
It gets $country from a $_GET.
_townselect.php
$towns= $this->townsselect($country);
$this->widget('bootstrap.widgets.TbSelect2', array(
'name'=>'clienttown',
'asDropDownList' => true,
'data' => $towns
));
townsselect() creates an array structured as: $towns[town-id]='TownName'
When the page is loaded normally it also runs the previous renderPartial with $country set manually as a default.
So it is calling the same code both times. However on page load the Tbselect2 is shown correctly (correct styling, includes js support which gives it a search box, etc...), but when I use ajax a standard Select is used with limited styling. In fact the code produced is different:
Result after page load
<div class="select2-container" id="s2id_clienttown" style="width: 220px">
<a href="#" onclick="return false;" class="select2-choice" tabindex="-1">
<span>Accrington</span>
<abbr class="select2-search-choice-close" style="display:none;"></abbr>
<div>
<b></b>
</div>
</a>
<div class="select2-drop select2-with-searchbox select2-drop-active select2-offscreen" style="display: block;">
<div class="select2-search">
<input type="text" autocomplete="off" class="select2-input" tabindex="-1">
</div>
<ul class="select2-results"></ul>
</div>
</div>
<select name="clienttown" id="clienttown" style="display: none;">
<option value="Select">Select</option>
...
</select>
</div>
Where as after the ajax only the Select is generated.
Temporary Solution
I managed to get this working in some form. Instead of recreating the whole select box I have altered the JQuery code to clear all options inside the Select and refill it with the new list.
The new list comes comes from a JSON string returned by the ajax. Which is processed as follows:
var towns = $.parseJSON(resp);
$('#clienttown option:gt(0)').remove(); //remove all options, but leave default 'Select A Town' option
var sel = $('#clienttown');
$.each(towns, function(id, town){
sel.append($("<option></option>").attr("value", id).text(town));
});
I've put this here in case it helps someone else trying to achieve a similar thing.
Howver I would still be interested to know why yiibooster/bootstrap does not work when rendered after ajax. And if there is a way to make it work, as this solution wont work unless the input is first rendered on page load.
I know this is old but have you tried the following to get the after Ajax rendering to work.
// Notice the ,false, true at the end of renderpartial
$this->renderPartial("_townsselect", array('country'=>$country), false, true);

Categories