Jquery post method - Auto populate two dropdown fields onchange - php

I have a dropdown select called 'Select Company' on change of which i would auto-populate the 'Locations' dropdown by fetching the company id from the table. Below is my PHP code that returns the results after querying for both the fields that need to be auto-populated :
$output = array();
if(!empty($data))
{
$out = "<select name='location' id='location'>";
$out .="<option value=''>Select a location</option>";
for($i=0;$i<count($data);$i++)
{
$out .="<option value='".$data[$i]['id']."'>".$data[$i]['location']."</option>";
}
$out .= "</select>";
}
else{
$out = "<select name='location' id='location'>";
$out .="<option value=''>No locations added</option>";
$out .="</select>";
}
$sql2 = "select id,username from client24_bcpfm.users where cid = '$cid'";
$data2 = return_results($sql2);
if(!empty($data2))
{
$out2 = "<select name='username' id='username'>";
$out2 .="<option value=''>Select a User</option>";
for($i=0;$i<count($data2);$i++)
{
$out2 .="<option value='".$data2[$i]['id']."'>".$data2[$i]['username']."</option>";
}
$out2 .= "</select>";
}
else{
$out2 = "<select name='username' id='username'>";
$out2 .="<option value=''>No Users</option>";
$out2 .="</select>";
}
$output['0'] = $out;
$output['1'] = $out2;
print_r(json_encode($output));
Part where i am stuck , using the jquery to iterate the two different arrays for two different fields :
$.post('locations2.php',{cid:cid},
function(data)
{
data = $.parseJSON(data);
$("#location").html(data);
return;
});
Please let me know how to return the php values for 2 dropdowns and also iterate through them in the front end jquery .

If you want to return an array, you can also do it like this:
echo json_encode(array(
"out1" => $out,
"out2" => $out2));
and get the values in jquery like this:
$.post('locations2.php',{cid:cid},
function(data)
{
data = $.parseJSON(data);
//first array
$("#location").html(data.out1);
//second array
$("#location").html(data.out2);
return;
});

Related

Php: Group and add missed field

I have in a array a table like this:
cid plugin lang_id name father
1 Newspage 1 Actualidad 1
1 Newspage 2 News 1
2 Newspage 1 Tecnologia 1
2 Newspage 2 Tech 1
3 Newspage 1 Deportes 1
3 Newspage 2 Sports 1
4 Newspage 1 Ocio 1
In this example there are two languages (1:Spanish and 2:English) but admin can add more languages
I want do a "modify category" section and group it by CID with input boxes for each language if language its missed i want display a empty input for add the missed language.
Something like this:
http://i.imgur.com/fGCUgKc.png
My actual bad code its this:
$content = "<div class='catlist'>";
$content .= "<p>{$LANGDATA['L_NEWS_MODIFIED_CATS']}</p>";
$query = $db->select_all("categories", array ("plugin" => "Newspage", "lang_id" => 1));
while ($cat_grouped = $db->fetch($query)) {
$content .= "<form id='cat_mod' method='post' action=''>";
$content .= "<div>";
foreach ($langs as $lang) {
if ($lang['lang_id'] == $cat_grouped['lang_id']) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$cat_grouped['name']}' />";
} else {
$query2 = $db->select_all("categories", array ("plugin" => "Newspage", "cid" => "{$cat_grouped['cid']}", "lang_id" => "{$lang['lang_id']}"));
if($db->num_rows($query2) <= 0) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='' />";
} else {
$other_lang_cat = $db->fetch($query2);
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$other_lang_cat['name']}' />";
}
}
}
$content .= "<input type='hidden' name='cid' value='{$cat_grouped['cid']}' />";
$content .= "<input type='submit' name='ModCatSubmit' value='{$LANGDATA['L_NEWS_MODIFY']}' />";
$content .= "</div></form>";
}
$content .= "</div>";
This:
$db->select_all(...);
mean
$db->select_all("table", $WHERE, ...)
I want to retrieve all content in one query and do the work in php
My actual code its clearly very bad and assumed lang_id=1 exists for each entry and do few query's huh!
My old code use "GROUP BY cid" for the first query and not need to use "lang_id=1" but after a system upgrade that line give the error:
reported: Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column
and not want to use again that.
any idea the best way for do that?
I don't know what your database library is, so I'm writing a pseudo like code.
First, I would use a pagination to limit the database queries, for example 10/20 phrases for each page. So the query would be:
SELECT * FROM language_phrases WHERE cid IN (
SELECT DISTINCT cid FROM language_phrases WHERE plugin = 'Newspage'
LIMIT 0,10
)
then I would use the data from database first to get the cid values:
$cid = array();
$strings = array();
while($row = $db->fetch($result))
{
if(!in_array($cid,$row["cid"]))
{
$cid[] = $row["cid"];
}
$strings[]= array(
"cid" => $row["cid"],
"lang_id" => $row["lang_id"],
"name" => $row["name"],
"father" => $row["father"]
);
}
Then I would have the table and the distinct cid's in this page in my buffer. Then PHP will do the rest:
foreach($cid as $idx=>$key)
{
$values = array_filter($strings,function($d) use ($key) {
return $d["cid"] == $key;
});
// build the form with the $values array.
}
This problem give a headache but i made another version that work and only one query.
I will check later the Taha Paksu version/way (thanks!)
$content = "<div class='catlist'>";
$content .= "<p>{$LANGDATA['L_NEWS_MODIFIED_CATS']}</p>";
$query = $db->select_all("categories", array ("plugin" => "Newspage"), "ORDER BY cid");
$cats = [];
$catsids = [];
while ($cats_row = $db->fetch($query)) {
$cats[] = $cats_row;
$catsids[] = $cats_row['cid'];
}
$catsids = array_unique($catsids);
$foundit = 0;
foreach ($catsids as $catid) {
$content .= "<form id='cat_mod' method='post' action=''>";
$content .= "<div>";
foreach ($langs as $lang) {
foreach ($cats as $cat) {
if (($catid == $cat['cid']) && ($cat['lang_id'] == $lang['lang_id'])) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$cat['name']}' />";
$foundit = 1;
}
}
if ($foundit == 0) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='' />";
}
$foundit = 0;
}
$content .= "<input type='hidden' name='cid' value='$catid' />";
$content .= "<input type='submit' name='ModCatSubmit' value='{$LANGDATA['L_NEWS_MODIFY']}' />";
$content .= "</div></form>";
}

Creating combobox and checkboxes with jQuery and CodeIgniter

I have combobox named catid, which is filled with categories. On change, I am filling the content on other
2 comboboxes and I am adding checkboxes in my form, which are all based on selected category.
So three comboboxes in total, categories (#catid), subcategories (#catid2) and manufacturers (#manufacturerid)
in this order.
When there are no subcategories, everything is nice and smooth. In the subcategory combobox, i get the message
there are no subcategories, i am filling the manufacturers combobox with manufacturers from that category,
and i am drawing the comboboxes again related to this category.
Problem arise when sub category exist. I am trying using on change event to fetch my checkboxes, related to that subcategory.
I get undefined value.
Here is my code:
Controller:
public function __construct() {
parent::__construct();
$this->load->model('addsCategoriesModel');
$this->load->model('addsTypesModel');
$this->load->model('colorsModel');
$this->load->model('geographicAreasModel');
$this->load->model('categoriesFiltersModel');
}
// function index has been ommited for the sake of simplicity
function get_dropdown_values($catid){
$this->load->model('manufacturersModel');
$this->db->select('manufacturerid,manufacturername');
$this->db->where("catid = $catid");
$result = $this->manufacturersModel->get();
//echo form_dropdown('manufactirerid', $result, NULL, 'id="manufacturerid"');
echo "<select name='manufacturerid' id='manufacturerid' class='styled_select'>";
//"<option value=".$result[]['manufacturerid'].">".$result[]['manufacturername']
foreach ($result as $key=>$value) {
echo "<option value=".$key['manufacturerid'].">".$value['manufacturername']."</option>";
}
echo "</select>";
}
function get_dropdown_values2($catid){
// create the second drop down, where parent id is the selected category
$this->db->select('catid,parentid,categoryname');
$this->db->where("parentid = $catid");
$result2 = $this->addsCategoriesModel->get();
if(count($result2) > 0){
echo "<select name='catid2' id='catid2' class='styled_select'>";
foreach ($result2 as $key=>$value) {
echo "<option value=".$key['catid'].">".$value['categoryname']."</option>";
}
echo "</select>";
} else {
echo "<select name='catid2' id='catid2' class='styled_select'>";
echo "<option value='0'>No subcategories</option>";
echo "</select>";
}
}
function get_categories_filters($catid3){
// create the checkboxes according to selected category
// case 1: if the category id is NOT 4
$this->db->where("catid = $catid3");
$result3 = $this->categoriesFiltersModel->get();
if(count($result3) > 0){
// start the foreach loop
foreach($result3 as $key=>$value){
echo "<div class='chb_group'>";
echo "<span class='custom_chb_wrapper'>";
echo "<input type='checkbox' name=" .$value['filterid'] ." class='zcheckbox'/>";
echo "<label>" .$value['filtername']. "</label>";
echo "</span>";
echo "</div>";
}
} else {
$result3 = "No checkboxes in this category";
echo $result3;
//$this->get_categories_filters2(22);
}
}
function get_categories_filters2($catid4){
// create the checkboxes according to selected category
$this->db->where("catid = $catid4");
$result4 = $this->categoriesFiltersModel->get();
if(count($result4) > 0){
// start the foreach loop
foreach($result4 as $key=>$value){
echo "<div class='chb_group'>";
echo "<span class='custom_chb_wrapper'>";
echo "<input type='checkbox' name=" .$value['filterid'] ." class='zcheckbox'/>";
echo "<label>" .$value['filtername']. "</label>";
echo "</span>";
echo "</div>";
}
} else {
//$result4 = "No checkboxes in this category";
$result4 = "Are you in filters2??";
echo $result4;
}
}
}
Here is my view:
<select name="catid" id="catid" class="styled_select" onchange="load_dropdown_content($('#manufacturerid'), this.value);load_dropdown_content2($('#catid2'), this.value);load_dropdown_content3($('#catid3'), this.value);">
<option value="0">Please select</option>
<?php
// foreach loop to fetch the categories
foreach ($adds_categories as $category){
echo "<option value=".$category['catid'].">".$category['categoryname']."</option>";
}
?>
</select>
</div>
<div class="select_wrapper">
<label><strong>Subcategory: </strong></label>
<select name="catid2" id="catid2" class="styled_select" onchange="load_dropdown_content4($('#catid3'), this.value);">
<option value="0">Please select</option>
</select>
</div>
For the sake of simplicity, I am not showing here the manufactirer combobox, with which i have no problem whatsoever and the checkboxes
And the javascript:
<script type="text/javascript">
function load_dropdown_content(field_dropdown, selected_value){
var result = $.ajax({
'url' : '<?php echo site_url('submit/get_dropdown_values'); ?>/' + selected_value,
'async' : false
}).responseText;
field_dropdown.replaceWith(result);
}
function load_dropdown_content2(field_dropdown, selected_value){
var result2 = $.ajax({
'url' : '<?php echo site_url('submit/get_dropdown_values2'); ?>/' + selected_value,
'async' : false
}).responseText;
field_dropdown.replaceWith(result2);
}
function load_dropdown_content3(field_dropdown, selected_value){
if(selected_value == 4){
load_dropdown_content4();
}
var result3 = $.ajax({
'url' : '<?php echo site_url('submit/get_categories_filters'); ?>/' + selected_value,
'async' : false
}).responseText;
$('#catid3').empty(); // DIV CATID3 IS THE DIV WHERE CHECKBOXES ARE CREATED
$("#catid3").append(result3);
}
function load_dropdown_content4(field_dropdown, selected_value){
var result4 = $.ajax({
'url' : '<?php echo site_url('submit/get_categories_filters2'); ?>/' + selected_value,
'async' : false
}).responseText;
$('#catid3').empty(); // DIV CATID3 IS THE DIV WHERE CHECKBOXES ARE CREATED
$("#catid3").append(result4);
alert(result4);
}
</script>
If anyone can help me to overcome that undefined error which I am getting from subcategories combobox, I will deeply appreciated.
Regards...
Instead of $("$cat3"), you can do like below also.
onchange = 'load_dropdown_content4("cat3",this.value)'
In load_dropdown_content4
function load_dropdown_content4(field_dropdown, selected_value)
{
//replace field_dropdown.replaceWith(result2);
$("#"+field_dropdown).replaceWith(result2);
}
Try this code.

How to set multiple select options by default from array

I'm trying to retrieve options/values from my database in the from of an array i would like to set these option/values as selected by default in a multiple select list and display them to the user where they will be able to updated their data if necessary.
//data in database
$mytitle = array(
'Arbitrator',
'Attorney',
'Student',
'Other'
);
//data for multiple select
$title = array(
'Judge' ,
'Magistrate' ,
'Attorney' ,
'Arbitrator',
'Title Examiner' ,
'Law Clerk','Paralegal' ,
'Intern' ,
'Legal Assistant',
'Judicial Assistant',
'Law Librarian' ,
'Law Educator' ,
'Attorney',
'Student',
'Other'
);
echo "<select name='title[]' multiple='multiple'>";
$test = implode(',', $mytitle);
for ($i=0; $i<=14; $i++) {
if($test == $title[$i]) {
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}
else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
echo "</select>";
I think you may have a logic error. Try this as your loop:
foreach ($title as $opt) {
$sel = '';
if (in_array($opt, $mytitle)) {
$sel = ' selected="selected" ';
}
echo '<option ' . $sel . ' value="' . $opt . '">' . $opt . '</option>';
}
Use the in_array() function.
for ($i=0; $i<=14; $i++) {
if(in_array($title[$i], $mytitle)){
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
Very simple with the help of jQuery where the select has the id test
$('#test option').attr('selected', 'selected');
JSFiddle Example

Populate an associative select from a database

Here's my problem: I have two select fields in my web application.
The second one depends on the choice made on the first one. The first one is populated from my database with the classical:
<?php
//connection to database in an include file
$query = "SELECT DISTINCT platform
FROM Appversions";
$res = mysql_query($query);
while($row = mysql_fetch_array($res)) {
echo "<option value=\"\"" . $row['platform'] . "</option>\n";
}
?>
which is working just fine.
But then I need to populate my second select with a query that would look like:
SELECT version
FROM Appversions
WHERE platform = <choice made in first select>;
I understand that I need to use JavaScript with an onChange function call to do that, but I can't figure out what that function should look like or how it will have access to my query result.
Usually i have this jquery code:
$('#select1').change(function(){
if($(this).val() == ''){
$('#select2').attr('disabled', 'true');
}else{
var select1 = $(this).val();
$.getJSON('index.php',
{
option: "com_spin",
controller: "guest",
task: "getProvincieByRegionId",
idRegione: idRegione
},
function(json){
$('#select2').html(json.html);
}
);
$('#select2').removeAttr('disabled');
}
});
in php i have something like this (basically i return the html for the options:
Zend_Loader::loadClass ( 'Zend_Json' );
$idRegione = JRequest::getVar ( "idRegione" );
$modelProvince = new Spin_lkpprovincia ();
$provincie = $modelProvince->getElencoProvinciePerRegione ( $idRegione );
$html = "<option value=''>Selezionare una voce</option>";
foreach ( $provincie as $provincia ) {
$html .= "<option value='" . $provincia ['idProvincia'] . "'>" . $provincia ['nome'] . "</option>";
}
$json = array (
success => "OK",
html => $html );
$json = Zend_Json::encode ( $json );
echo $json;
die ();

Grabbing the right record in a drop down from mysql

I'm using a form where the user can edit an entry. Everything is populating and all is well with the exception that I can't get the drop down to show the project that they've already assigned the image to.
$project_qry = "SELECT * from projects ORDER BY title ASC";
$project_res = mysql_query($project_qry);
$project_drop = "<select name=\"project_id\">\n";
while ($row = mysql_fetch_array($project_res))
{
if ($project_id == $row[title])
{
$project_drop .= "<option value=\"$row[id]\" selected>$row[title]</option>\n";
}
else
{
$project_drop .= "<option value=\"$row[id]\">$row[title]</option>\n";
}
}
$project_drop .= "</select>\n";
I'm sure it's something devilishly simple but I'm stumped.
{
if ($project_id == $row[id])
{
$project_drop .= "<option value=\"$row[id]\" selected=\"selected\">$row[title]</option>\n";
}
else
{
$project_drop .= "<option value=\"$row[id]\">$row[title]</option>\n";
}
}
You need to compare the value and not the title. It is the value that gets posted ($_POST)
selected="selected" makes it XHTML compliant.
bigstylee answered correctly. I also recommend to separate the values of the array and your string:
$project_drop .= "<option value='". $row['id'] ."'>".$row['title']."</option>";
Also drop \n. Outputting \n won't generate a line break in the browser. And it is unnecessary.

Categories