auto populate data with dropdown - php

ALL EDITED
Hi,
How can I auto populate the data from db by dropdown selected? and my dropdown result already appear as well, the code as following:
<?php
echo '<tr>
<td>'.$customer_data.'</td>
<td><select name="customer_id" id="customer_id" onchange="getCustomer();">';
foreach ($customers as $customer) {
if ($customer['customer_id'] == $customer_id) {
echo '<option value="'.$customer['customer_id'].'" selected="selected">'.$customer['name'].'</option>';
} else {
echo '<option value="'.$customer['customer_id'].'">'.$customer['name'].'</option>';
}
}
echo '</select>
</td>
</tr>';
?>
has html view code as
<select name="customer_id" id="customer_id" onchange="getCustomer();">
<option value="8">admin</option>
<option value="6">customer1</option>
<option value="7" selected="selected">FREE</option>
</select>
now if one of dropdown selected i want another e.g. <?php echo $firstname; ?>, <?php echo
$lastname; ?>
appear in
<tr>
<td><div id="show"></div></td>
</tr>
that based on customer id/name selected
to do that i try to use json call as following:
<script type="text/javascript"><!--
function getCustomer() {
$('#show input').remove();
$.ajax({
url: 'index.php?p=customer/customers&customer_id=' + $('#customer_id').attr('value'),
dataType: 'json',
success: function(data) {
for (i = 0; i < data.length; i++) {
$('#show').append('<input type="text" name="customer_id" value="' + data[i]['customer_id'] + '" /><input type="text" name="firstname" value="' + data[i]['firstname'] + '" />');
}
}
});
}
getCustomer();
//--></script>
the php call json placed at customer.php with url index.php?p=page/customer)
public function customers() {
$this->load->model('account/customer');
if (isset($this->request->get['customer_id'])) {
$customer_id = $this->request->get['customer_id'];
} else {
$customer_id = 0;
}
$customer_data = array();
$results = $this->account_customer->getCustomer($customer_id);
foreach ($results as $result) {
$customer_data[] = array(
'customer_id' => $result['customer_id'],
'name' => $result['name'],
'firstname' => $result['firstname'],
'lastname' => $result['lastname']
);
}
$this->load->library('json');
$this->response->setOutput(Json::encode($customer_data));
}
and the db
public function getCustomer($customer_id) {
$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "customer WHERE customer_id = '" . (int)$customer_id . "'");
return $query->row;
}
but i get the wrong return as following
is there someone please how to solved it to more better? thanks in advance

Something on your PHP-Coding style:
For a PHP Code-Block, don't use new php-Tags for every line. Also, if you want an HTML-Output from PHP, you can use the echo-Method to do this. So your Code looks like this:
<?php
echo '<tr>
<td>'.$customer.'</td>
<td><select name="customer_id">';
foreach ($customers as $customer) {
if ($customer['customer_id'] == $customer_id) {
echo '<option value="'.$customer['customer_id'].'" selected="selected">'.$customer['name'].'</option>';
} else {
echo '<option value="'.$customer['customer_id'].'">'.$customer['name'].'</option>';
}
}
echo '</select>
</td>
</tr>';
?>
The thin is, every time the PHP-Interpreter finds an opening PHP-Tag, it starts Interpreting it's code, and when it finds a closing Tag, it stops doing this. So in your code, the interpreter starts and stops all the time. This is not very performance.
I guess you want to set the value of your text-fields? That's really not what PHP does. That is more a JavaScript thing, because it actually happens in the Browser, not on the Server.

Instead of this:
success: function(data) {
for (i = 0; i < data.length; i++) {
$('#show').append('<input type="text" name="customer_id" value="' + data[i]['customer_id'] + '" /><input type="text" name="firstname" value="' + data[i]['firstname'] + '" />');
}
}
in Your JS AJAX call do this:
success: function(data) {
$('#show').append('<input type="text" name="customer_id" value="' + data['customer_id'] + '" /><input type="text" name="firstname" value="' + data['firstname'] + '" />');
}
as Your PHP function returns ONLY ONE object. If You then loop over the objects property You loop over one character of the property value indeed...

Related

HTML/PHP form data validation?

I'm new at coding
Just looking for some help on this matter,
My code is a snippet from a table that I am designing
What i'm wanting to do is have the date input box disabled unless the first drop down = 'NO', the drop down data is pulled from an SQL query
<td><select name="DATEACC">
<?php
$options = array(' ','YES','NO');
$output = '';
for( $i=0; $i<count($options); $i++ ) {
$output .= '<option '
. ( $Row['custdateaccepted'] == $options[$i] ? 'selected="selected"' : '' ) . '>'
. $options[$i]
. '</option>';
}
echo $output;?>
</select></td>
<td><input type="date" name="ADVDATE" value="<?php echo $Row['dateadvised'];?>"></td>
Can anyone help?
Just disable your date input at the start
<input type="date" id="ADVDATE" name="ADVDATE" value="<?php echo $Row['dateadvised'];?>" disabled>
and enable it using js/jquery when you have your desired value in dropdown
$('[name=DATEACC]').change(function(){
if($(this).val() == 'DESIRED_VALUE')
$('[name=ADVDATE]').enable();
});
You need to use javascript for this. If you have a unique row id $rowid as 1,2,3 etc
<td><select name="DATEACC" onChange="dateEnable(this)" id="DATEACC_$Row['id']">
<?php
$options = array(' ','YES','NO');
$output = '';
for( $i=0; $i<count($options); $i++ ) {
$output .= '<option value="'.$options[$i].'"'
. ( $Row['custdateaccepted'] == $options[$i] ? 'selected="selected"' : '' ) . '>'
. $options[$i]
. '</option>';
}
echo $output;?>
</select></td>
<td><input id="ADVDATE_$Row['id']" type="date" name="ADVDATE" value="<?php echo $Row['dateadvised'];?>"></td>
in javascript
function dateEnable(dropdown){
var id = dropdown.id;
var rowid = id.split('_');
var myselect_value = dropdown.value;
if(myselect_value == 'NO') {
document.getElementById('ADVDATE'+'_'+rowid[1]).disabled = true;
} else {
document.getElementById('ADVDATE'+'_'+rowid[1]).disabled = false;
}
}
Without using jQuery you could try:
javascript
function enabletextfield(e){
var el=typeof( e.target )!=='undefined' ? e.target : e.srcElement;
var value=el.options[ el.options.selectedIndex ].value;
var txtfield=document.querySelectorAll('input[type="date"][name="ADVDATE"]')[0];
txtfield.disabled = value=='NO' ? false : true;
}
html
<select name='DATEACC' id='DATEACC' onchange='enabletextfield(event)'>
<option value='MAYBE'>MAYBE
<option value='NO'>No
<option value='Yes'>Yes
</select>
<input type="date" name="ADVDATE" value="Some value or other" disabled=true />
Obviously change the name of the select menu to suit and add the correct value from the db to the date input box

Pass a value to my function in php

I have a list of products in a table extracted from my DB.
Each product have a field with ALIQUOTA (= VAT, Tax).
I want to have the possibility to modify the aliquote value assigned to single products.
I did a drop menu next to the actual aliquote that contains all the allowed value from an aliquote table of my database. (that values are 0.00, 4.00, 10.00, 20.00).
Once selected, that value will be inserted in a readonly input text field with id "aliquota_XXX" (where XXX is the id that correspond to the product).
Then i want to save that value pressing the button CONFIRM VAT that activate the function save_modify (this function already exists in the project).
This is the code:
<select class="piccolo elemento_modulo_obbligatorio" id="aliquota_dropdown_<?php echo $row['rid']; ?>" name="aliquota_dropdown">
<?php
$aliquote = "SELECT aliquota,id AS aid FROM aliquote ORDER BY aliquota ASC";
$result_aliquote = mysql_query($aliquote) or die("Invalid query: " . mysql_error());
while ($row_aliquote = mysql_fetch_array($result_aliquote)) {
echo '<option onclick=\'';
?>
$("#aliquota<?php echo $row['rid']; ?>").val("<?php echo $row_aliquote['aliquota']; ?>");
<?php
echo ';\' value="' . $row_aliquote['aid'] . '">' . $row_aliquote['aliquota'] . '</option>';
}
?>
</select>
<input autocomplete="off" type="text" class="class12" id="aliquota<?php echo $row['rid']; ?>" name="aliquota" readonly="readonly" value="" />
<input type="button" onclick="save_modify("aliquota",document.getElementById('aliquota_<?php echo $row['rid']; ?>').value,<?php echo number_format($row['aliquota'],2,".",","); ?>);" value="CONFIRM VAT" />
The function save_modify is that:
function save_modify(cosa, valore_nuovo, valore_vecchio) {
$.ajax({
type: "GET",
url: "ajax_salva_modifica_valore.php",
data: "id_documento=" + <? php echo $_GET['id_documento']; ?> +"&cosa=" + cosa + "&id=" + id + "&valore_nuovo=" + valore_nuovo + "&valore_vecchio=" + valore_vecchio,
cache: false,
success: function(data) {
$("#sezione_messaggi").html("Succesfully modified!");
},
beforeSend: function() {
$("#sezione_loading").html("<img src='../images/ajax-loader.gif' />");
},
complete: function() {
$("#sezione_loading").html("");
post_modifica(id);
carica_righe();
}
});
}
And the part of ajax_salva_modifica_valore.php that interest that is:
<?php
session_start();
$cosa = $_GET['cosa'];
$array_id = split("_",$id);
$id_riga = $array_id[1];
$valore_nuovo = $_GET['valore_nuovo'];
$valore_vecchio = $_GET['valore_vecchio'];
if($cosa == "aliquota") {
$modifica = "UPDATE righe_documenti
SET aliquota = '" . $valore_nuovo . "'
WHERE id = " . $id_riga;
$result = mysql_query($modifica) or die("Invalid query: " . mysql_error());
}
?>
I don't know where is the problem, because the parameter passed to the function are correct, but the modify it's not applied...
Someone can help me to fix it or try another solution?
The save_modify and ajax_salva_modifica_valore.php are not made by me, so i suppose that them are correct (and they works for the edit of other products information...)
Thanks!
The main problem is that number_format() formats number as a string and should be enclosed in double quotes (") in your case.
<input type="button" onclick="save_modify("aliquota",this.id,$("#aliquota<?php echo $row['rid']; ?>").val(),"<?php echo number_format($row['aliquota'],2,",","."); ?>");" value="CONFIRM ALIQUOTA" />
However by looking at the rest of your code, it seems you don't need number_format() at all:
<input type="button" onclick="save_modify("aliquota",this.id,$("#aliquota<?php echo $row['rid']; ?>").val(),<?php echo $row['aliquota']; ?>);" value="CONFIRM ALIQUOTA" />

Jquery issue, have to double click for the toggle to occur, can you tell me why?

All else is working fine
jQuery:
$(".edit").click(function()
{
var user_id=$(this).attr('id');
var options = '';
$.getJSON("do_find_courses.php",{user_id:user_id}, function(data){
for (var i = 0; i < data.length; i++) {
if(data[i].optionDisplay=="No File Categories")
{
options = '<option disabled="disabled" selected="selected">No products</option>';
}
else
{
options +=' <input name="' + data[i].optionValue + '" type="checkbox" value="' + data[i].optionDisplay + '" />'+ data[i].optionDisplay +'<br>';
//options += '<option value="' + data[i].optionValue + '">' + data[i].optionDisplay + '</option>';
}
}
$("#chkbox"+user_id).slideToggle( "slow" ).html(options);
//$("#chkbox"+user_id).html(options);
});
return false;
});
php code generated for the a href
<?php
$get_students=mysql_query("SELECT user_id ,surname,name, admin FROM users WHERE users.admin=0 ORDER BY users.surname ASC") or die(mysql_error());
while($row=mysql_fetch_array($get_students))
{
echo'
<tr>
<td><h3>'.$row['surname'].'</h3></td>
<td>'.$row['name'].'</td>
<td><div id="chkbox'.$row['user_id'].'"></div></td>
<td>Delete
Edit</td>
</tr>';}
?>
$(document).ready(function{
$(".edit").unbind('click');
$(".edit").click(function(){ bla bla bla});
});

maintain the choices after submit in ajax concatenated select

I made a form with some dynamic/concatenated select in this way.
FORM HTML (index.php)
<form id="src_form" action="index.php" method="post">
<p>
<select name="catid_1" id="catid_1" class="fieldmax">
<?php echo $cs->show_cat_1(''); ?>
</select>
</p>
<p>
<select name="catid_2" id="catid_2" class="fieldmax">
<option value=""> </option>
</select>
</p>
<p>
<select name="catid_3" id="catid_3" class="fieldmax">
<option value=""> </option>
</select>
</p>
<p>
<input type="submit" name="submit" value="SRC" id="btn_src">
</p>
</form>
AJAX JS
$(function() {
// Ajax post Page
var urlpage = 'ajax-php/con-select.php';
// Vars
var wait = '<option value="">wait</option>';
var all = '<option value="">all</option>';
// Default
$("select#catid_2").prop("disabled", true);
$("select#catid_3").prop("disabled", true);
// CATID_1 Change
$("select#catid_1").change(function(){
// set var
var catid_1 = $("select#catid_1 option:selected").prop("value");
// laod
$("select#catid_2").html(wait);
$.post(urlpage,
{
catid_1:catid_1
},
function(data){
switch (data) {
case all:
$("select#catid_2").html("");
return false;
default:
$("select#catid_2").prop("disabled", false);
$("select#catid_2").html(data);
return false;
}
});
});
// CATID_2 Change ... etc
});
CON-SELECT.PHP
if(isset($_POST['catid_1']))
{
echo $cs->show_cat_2();
die;
}
if(isset($_POST['catid_2']));
{
echo $cs->show_cat_3();
die;
}
CLASS.PHP
public function show_cat_1()
{
$result = $this->db->mysqli->query
("SELECT * FROM cat_1 ORDER BY idcat_1 ASC");
$cat_1 = '<option value="">all</option>';
while($row = $result->fetch_assoc())
{
$cat_1 .= '<option value="' . $row['idcat_1'] . '"';
$cat_1 .= '>' . $row['idcat_1'] . '</option>';
}
return $cat_1;
}
public function show_cat_2()
{
$result = $this->db->mysqli->query
("SELECT * FROM cat_2 ORDER BY idcat_2 ASC");
$cat_2 = '<option value="">all</option>';
while($row = $result->fetch_assoc())
{
$cat_1 .= '<option value="' . $row['idcat_2'] . '"';
$cat_1 .= '>' . $row['idcat_2'] . '</option>';
}
return $cat_2;
}
etc..
my goal is to keep the choices (select value) in fields after submit the form (reload page) while maintaining their functionality. you can do it? how could I do that? thanks

Make div appear on dynamic option select

I have a SELECT input that gets all of its options via the database. Below the select input, there are divs created for each option in the select. I want the user to select an option from the drop down and make the div below display. So basically the drop down are sports, and if they make a selection the sport div hidden below will load, and that div will contain all the sport positions
<select name="sport" id="select">
<?
foreach ($getSports as $row) {
echo '<option onClick="toggle'.$row['1'].'()" onLoad="toggle'.$row['1'].'()" value="' . $row['0'] . '">' . $row['1'] . '</option>';
}
?>
</select>
</label>
<?
foreach ($getSports as $row) {
echo '<div id="position' . $row['1'].'" style="margin-top: 5px;display:none;">Positions:' . $row['1'].'';
$sport = $row['0'];
$getPositions = $model->getPositions($sport);
foreach ($getPositions as $row2) {
echo '<label style="float:right">'.$row2['1'].'</label>';
echo '<input type="checkbox" name="'.$row2['1'].'" value="'.$row2['0'].'">';
}
echo '</div>';
}
?>
How about modifying your code like this? Seems to be more semantic:
<select name="sport" id="select">
<? foreach ($getSports as $row) {
echo '<option data-row-id="'.$row['1'].'" value="'.$row['0'].'">'.$row['1'].'</option>';
} ?>
</select>
</label>
<? foreach ($getSports as $row) {
echo '<div data-position="'.$row['1'].'" style="margin-top:5px;display:none;">Positions:' . $row['1'].'';
$sport = $row['0'];
$getPositions = $model->getPositions($sport);
foreach ($getPositions as $row2) {
echo '<label style="float:right">'.$row2['1'].'</label>';
echo '<input type="checkbox" name="'.$row2['1'].'" value="'.$row2['0'].'">';
}
echo '</div>';
}?>
<script>
$(function() {//create the binding once the document is ready
$('#select').change(function() {
var select = $(this);
var selectedOption = select.find(':selected');
var position = selectedOption.attr('data-row-id');
var divContext = $('[data-position="'+position+'"]');
$('[data-position]').not(divContext).hide();
divContext.show();
});
});
</script>
If you want to keep visible only the selected sport, I suggest this.
(1) add a class to the div which holds sports information - ex. class="sportsHolder"
(2) change this part
onClick="toggle'.$row['1'].'()" onLoad="toggle'.$row['1'].'()"
to
onClick="toggle('.$row['1'].');" onLoad="toggle('.$row['1'].');"
(3) create the function
<script type="text/javascript">
function toggle(whichPos) {
$(".sportsHolder").hide();
$("#position" + whichPos).show();
}
</script>
at least I would do it that way.

Categories