maintain the choices after submit in ajax concatenated select - php

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

Related

Codeigniter: need help getting my filter to work

Hi I need help with my filtering system. when a user selects a filter it loads the information but doesn't refresh the page with the results. the pictures below are what im looking to do.
Heres some images of what the page will look like
Heres my code
JS
code
(function($) {
"use strict";
var ProposalServerParams = {
"status_filter": "[name='change_status[]']",
"trade_filter": "[name='reade_filter[]']",
"City_filter": "[name='city_filter']",
"post_code_filter_: "[name='post_code_filter[]']",
};
var table_rec_candidate = $('.table-table_rec_candidate');
initDataTable('.table-table_rec_candidate', admin_url+'recruitment/table_candidates', [0], [0], ProposalServerParams, [0, 'desc']);
//hide first column
var hidden_columns = [0];
$('.table-table_rec_candidate').DataTable().columns(hidden_columns).visible(false, false);
$.each(ProposalServerParams, function(i, obj) {**strong text**
$('select' + obj).on('change', function() {
table_rec_candidate.DataTable().ajax.reload();
});
});
code
Controller
code
public function candidate_profile() {
if ($this->input->get('kanban')) {
$this->switch_kanban(0, true);
}
$data['switch_kanban'] = false;
$data['bodyclass'] = 'tasks-page';
if ($this->session->userdata('candidate_profile_kanban_view') == 'true') {
$data['switch_kanban'] = true;
$data['bodyclass'] = 'tasks-page kan-ban-body';
}
$data['rec_campaigns'] = $this->recruitment_model->get_rec_campaign();
$data['candidates'] = $this->recruitment_model->get_candidates();
$data['skills'] = $this->recruitment_model->get_skill();
$data['job_titles'] = $this->recruitment_model->get_job_position();
$data['company_list'] = $this->recruitment_model->get_company();
$data['title'] = _l('candidate_profile');
$this->load->view('candidate_profile/candidate_profile', $data);
}
code
View code
code
<div class="row">
<div class="col-lg-2 ">
<div class="form-group">
<select name="trade_filter" id="trade_filter" class="selectpicker" data-live-search="true" data-width="100%" data-none-selected-text="<?php echo _l('trade'); ?>">
<option value="" ><?php echo _l('trade'); ?></option>
<?php foreach($trade as $trade_key => $trade){ ?>
<option value="<?php echo html_entity_decode($trade['id']); ?>" > <?php echo html_entity_decode($trade['trade']); ?></option>
<?php }?>
</select>
</div>
</div>
View for data tables
$trade_filter = $this->ci->input->post('trade_filter');
if(isset($trade_filter)&&($trade_filter!='')){
$trade_where = '';
foreach ($trade_filter as $tarde_id) {
if ($trade_id != '') {
if ($trade_where == '') {
$trade_where .= 'AND (find_in_set(' . $trade_id . ', ' . db_prefix() . 'rec_candidate.trade) ';
} else {
$rade_where .= ' OR find_in_set(' . $trade_id . ', ' . db_prefix() . 'rec_candidate.trade) ';
}
}
}
if ($trade_where != '') {
$trade_where .= ')';
$where[] = $trade_where;
}
}

Populate 2nd select deoending of option choosen in 1st select

Im trying to use PHP+MySQL+Ajax to dynamically load options in a select but I don't know how to do it
Currently I have 2 select inside 2 forms and i need to send form 2 times, so the page will load 2 times.
I want to improve my code using ajax, so my page will load faster and will be easier to use.
Select 1 have a list of countries
Select 2 have a list of cities from the country selected in select 1
After you select the city, specific info from that city will be displayed in screen.
Form 1
<?php include_once "conn.php"; ?>
<!-- Form 1 -->
<form action="" method="post">
<select required id="Countries" name="Countries">
<?php
$sql = "SELECT distinct Country FROM cities order by 1 asc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row["Country"] . '">' . $row["Country"] . '</option>';
}
} else {
echo "0 results";
}
?>
</select>
<input type="submit" id="LoadCities" name="LoadCities" value="Load Cities" />
</form>
Form 2
<!-- Store select 1 value in variable -->
<?php
if (isset($_POST['Countries'])) {
$Countries = $_POST['Countries'];
}
?>
<!-- Form 1 -->
<form action="" method="post">
<select required id="Cities" name="Cities">
<?php
$sql = 'SELECT * FROM cities where country="' . $Countries . '"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row["City"] . '">' . $row["City"] . '</option>';
}
} else {
echo "0 results";
}
?>
</select>
<input type="submit" id="ShowInfo" name="ShowInfo" value="ShowInfo" />
</form>
Display City info on screen:
<!-- Store select 2 value in variable and print selected options in screen-->
<?php
if (isset($_POST['Cities'])) {
$City = $_POST['Cities'];
$sql = 'SELECT * FROM cities where City="' . $City . '"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<p>Country: ' . $row["Country"] . '</p>';
echo '<p>City: ' . $row["City"] . '</p>';
}
} else {
echo "0 results";
}
}
?>
For Ajax to work without you refreshing or submitting the forms. You need to create separate endpoints for your ajax calls. You should have 3 files:
index.php - Display the country form, city form and city info altogether here. The country data will load by default and other data will be linked to their respective Ajax calls.
fetchCities.php - Use this endpoint to fetch the dropdown values of cities based on the selected country value.
cityInfo.php - Use this endpoint to fetch the city information based on the selected city value.
Note: You can combine fetchCities.php and cityInfo.php into a single file if you include a second parameter in your Ajax call, for eg: action: "fetchCity"
Here's what you can do:
index.php
<?php include_once "conn.php"; ?>
<form action="" method="post">
<select required id="Countries" name="Countries">
<?php
$sql = "SELECT distinct Country FROM cities order by 1 asc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row["Country"] . '">' . $row["Country"] . '</option>';
}
} else {
echo "0 results";
}
?>
</select>
<input type="submit" id="LoadCities" name="LoadCities" value="Load Cities" />
</form>
//empty city dropdown. You may remove the form element from it if not required.
<form action="" method="post">
<select required id="Cities" name="Cities">
<option disabled selected>Select a country first</option>
</select>
</form>
//empty city info
<div id="cityInfo"></div>
<script>
//whenever someone selects a country, hit the Ajax to fetch cities.
$(document).on('change', '#Countries', function() {
const selectedCountry = $(this).val();
//run your cities Ajax here and pass selectedCountry value
$.ajax({
method: "POST",
url: "fetchCities.php",
data: {
Countries: selectedCountry
}
})
.done(function(response) {
//replace City dropdown with values returned from fetchCities.php file.
$('#Cities').html(response);
});
});
//whenever someone selects a city, hit the Ajax to fetch city information.
$(document).on('change', '#Cities', function() {
const selectedCity = $(this).val();
//run your cities Ajax here and pass selectedCity value
$.ajax({
method: "POST",
url: "cityInfo.php",
data: {
Cities: selectedCity
}
})
.done(function(response) {
$('#cityInfo').html(response);
});
});
</script>
fetchCities.php
<?php include_once "conn.php";
if (isset($_POST['Countries'])) {
$Countries = $_POST['Countries'];
$sql = 'SELECT * FROM cities where country="' . $Countries . '"';
$result = $conn->query($sql);
$returnHtml = '';
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$returnHtml .= '<option value="' . $row["City"] . '">' . $row["City"] . '</option>';
}
} else {
$returnHtml = '<option disabled selected>0 results</option>';
}
echo $returnHtml;
}else{
echo '<option disabled selected>0 results</option>';
}
?>
cityInfo.php
<?php
include_once "conn.php";
if (isset($_POST['Cities'])) {
$City = $_POST['Cities'];
$sql = 'SELECT * FROM cities where City="' . $City . '"';
$result = $conn->query($sql);
$returnHtml = '';
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$returnHtml .= '<p>Country: ' . $row["Country"] . '</p>';
$returnHtml .= '<p>City: ' . $row["City"] . '</p>';
}
echo $returnHtml;
} else {
echo "0 results";
}
}else{
echo "0 results";
}
?>
Also, as Dharman mentioned, you should really use parameterized queries. I know that seems like some extra work but trust me, it will be worth your time.
(Too long for a Comment.)
Let me get this straight. On a single page:
The page is initialized with a list of all countries. (Either when building the page, or via AJAX.)
The user selects one country from a list of all the countries.
A second database lookup finds the cities in that country.
Then something is done with those cities.
That must be two lookups.
Since you mentioned AJAX, you want to do all this without reloading the page? Be aware that <form> wants to reload the page. Yes you can pervert to do AJAX, but why have <form> if you won't be submitting and reloading the page?
The complete list of cities in the world is over 3 million. Are you working with that sized table? Or some subset, such as "cities that have a Burger King in it"?

How to get dynamic values by id -jquery

Actually, I have a field name (industry) the problem is that I want to get two value from the database change of industry by jquery but how do I do this can't understand. Please help-
Here is my code-
<label>Select Type of Industry</label>
<select class="form-control" name="industry" id="industry" onchange="industry_id(this.value);" required="">
<option value="">------------------Select Your Industry----------------</option>
<?php
foreach ($industry as $key => $value) { ?>
<option value="<?= $value['id']; ?> "> <?= $value['industory']; ?></option>
<?php } ?>
</select>
</div>
<script>
function industry_id(value) {
$.get("<?php echo base_url()?>dive/getebitvalue/"+value,function (data) {
$("#ebit_name").html(data);
// alert(data);
});
}
</script>
one value I get easily but how to get second from the same id?
Here is my model---
function getebit()
{
$industry=$this->uri->segment(3);
$sql = $this->db->query('SELECT * FROM industry WHERE id='.$industry);
$result = $sql->result();
$html='';
foreach ($result as $data) {
$html.= "<option value='" . $data->ebit . "' >" . $data->ebit . "</option>";
}
echo $html;
}
}
and here is my controller--
function getebitvalue(){
$data['ebit']= $this->site_model->getebit();
}
Method getebitvalue in controller should be like this :
function getebitvalue()
{
$industry_id = $this->uri->segment(3);
$result = $this->site_model->getebit($industry_id);
$html='';
if ( !empty($result)){
foreach ($result as $item)
{
$edita[$key] = $item->edita;
$html.= "<option value='" . $item->ebit . "' >" . $item->ebit . "</option>";
}
$data['edita'] = $edita;
$data['html'] = $html;
print_r($data);
exit;
}
}
Here is your model---
function getebit($industry_id)
{
$sql = $this->db->query('SELECT * FROM industry WHERE id='.$industry);
$result = $sql->result();
return $result;
}
You can also do this-
view page-
<div class="form-group">
<label>Select Type of Industry</label>
<select class="form-control industryData" name="industry" id="industry" required="">
<option value="">------------------Select Your Industry----------------</option>
<?php
foreach ($industry as $value) { ?>
<option data1="<?php echo $value['ebitda']; ?>" data2="<?php echo $value['ebit']; ?>" value="<?= $value['id']; ?>"> <?= $value['industory']; ?></option>
<?php } ?>
</select>
</div>
model page-
function select($tbl,$con=''){
$this->db->select("*");
$this->db->from($tbl);
if(!empty($con))
$this->db->where($con);
$query = $this->db->get();
return $query->result();
}
controller page-
public function dive(){
$this->load->view('common/header');
$data['industry'] = $this->site_model->select('industry');
$this->load->view('dive/dive',$data);
$this->load->view('common/footer');
}
Now use jquery on your view page--
<script>
$(document).on("change", ".industryData", function () {
var value = $(this).val();
var data1 = $('.industryData option:selected ').attr('data1');
var data2 = $('.industryData option:selected ').attr('data2');
alert(data1);
});
</script>

I cant load second drop down menu, when the first one is changed. The second drop down is depended on the first one

Here is my code, which is having a problem displaying the values of the second:
HTML: my form, the first drop down I get the elements from the database with query.
<form name="farmer" action="index.php" method="post">
<label>
<span>Chose Land:</span>
<select name="land" id="land">
<option value="">--land--</option>
<?php
$sql="SELECT `city` FROM `lands`";
$result =mysql_query($sql);
while ($data=mysql_fetch_assoc($result)){
?>
<option value ="<?php echo $data['city'] ?>" ><?php echo $data['city'] ?></option>
<?php } ?>
</select>
</label>
<label>
<span>Region:</span>
<select name="region" id="region">
<option value="">--region--</option>
</select>
</label>
<input class="button4" type="submit" name="submit" value="Submit" />
</form>
JS
jQuery(document).ready(function() {
jQuery('#land').change(function() {
jQuery.post(
'getList.json.php', {
'land': jQuery('#land').val()
},
function(data, textStatus) {
jQuery('#region').empty();
if(data != null)
{
jQuery.each(data, function(index, value) {
jQuery('#region').append('<option value="' + value + '">' + value + '</option>');
});
}
else {
jQuery('#region').append('<option value="">Please select...</option>');
}
},
'json'
);
});
});
getList.json.php file - Here I make connection between region and land with query(JOIN).
<?php
mysql_connect("localhost", "root", "") or die( "Unable to connect to database");
mysql_select_db("farmer_fields") or die( "Unable to select database");
if($_POST && $_POST['land'] != "") {
$sql="SELECT region FROM regions
LEFT JOIN lands
ON regions.id_lands = lands.id";
$rows = array();
while ($data=mysql_fetch_assoc($sql)){
$rows['region'] = $data;
}
echo json_encode( $rows );
}
?>
No need of json here. You can simply do with jquery and ajax
jquery:
function get_region(country_id) {
if (country_id != 0) {
$("#region_id").html("<option value='0'>Select Region</option>");
$("#region_id").prop("disabled", true);
$.post("ajax/ajax.php", {
country_id: country_id
}, function (data) {
var data_array = data.split(";");
var number_of_name = data_array.length - 1;
var value;
var text;
var opt;
var temp_array;
for (var i = 0; i < number_of_name; i++) {
temp_array = data_array[i].split(",");
value = temp_array[1];
//alert(value);
text = temp_array[0];
opt = new Option(text, value);
$('#region_id').append(opt);
$(opt).text(text);
}
$("#region_id").prop("disabled", false);
});
} else {
$("#region_id").html("<option value='0'>Select Region</option>");
$("#region_id").prop("disabled", true);
}
}
ajax file that is ajax.php
if (isset($_POST["country_id"])) {
$country_id = $_POST["country_id"];
$region_select = mysql_query("select * from region where country_id='$country_id'");
$region = "";
$region_id = "";
while ($region_row = mysql_fetch_array($region_select)) {
$region = $region.$region_row["region"].
",".$region_id.$region_row["id"].
";";
}
echo $region;
}
HTML OF REGION SELECT BOX:
<select name="region_id" id="region_id" disabled="disabled">
<option value="0">Select Region</option>
</select>
You may change mysql_query to PDO for security purpose as mysql_query is depriciated.
Check this, works for me.
JS:
jQuery(document).ready(function() {
var region = jQuery('#region');
var land = jQuery('#land').change(function() {
jQuery.post(
'getList.json.php', {
'land': land.val()
},
function(data) {
jQuery('#region').empty();
if (data != null) {
region.append(data);
}
else {
region.append('<option value="">Please select...</option>');
}
},
'html'
);
});
});
PHP:
if($_POST && $_POST['land'] != "") {
$sql="SELECT region
FROM regions r
LEFT JOIN lands l ON r.id_lands = l.id
WHERE l.city = " . $_POST['land'];
$result = mysql_query($sql); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< UPD!
while ($data = mysql_fetch_assoc($result)) {
echo '<option value="' . $data['region'] . '">' . $data['region'] . '</option>';
}
}

How do I select value from DropDown list in PHP??? Problem

I want to know the error in this code
The following code retrieves the names of the members of the database query in the
dropdownlist
But how do I know who you selected.... I want to send messages only to the members that selected form dropdown list
<?php
include ("connect.php");
$name = $_POST['sector_list'];
echo $name ;
?>
<form method="POST" action="" >
<input type="hidden" name="sector" value="sector_list">
<select name="sector_list" class="inputstandard">
<option size ="40" value="default">send to </option>
<?php
$result = mysql_query('select * from members ')
or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo '<option size ="40" value=" '. $row['MemberID'] . '" name="' . $row['MemberName']. '">' . $row['MemberName']. '</option>';
}
?>
</select>
</form>
I hope somebody can help me
This should do the trick.
<?php
$member_id = intval($_POST['sector_list']);
if($member_id == 0) {
// Default choice was selected
}
else {
$res = mysql_query("SELECT * FROM members WHERE MemberID = $member_id LIMIT 1");
if(mysql_num_rows($res) == 0) {
// Not a valid member
}
else {
// The member is in the database
}
}
?>
<form method="post" action="">
<input type="hidden" name="sector" value="sector_list">
<select name="sector_list" class="inputstandard">
<option value="0">send to</option>
<?php
$result = mysql_query('SELECT * from members') or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="' . $row['MemberID'] . '">' . $row['MemberName']. '</option>';
}
?>
</select>
</form>
To get an input to change when you select someone try this:
<select onchange="document.getElementById('text-input').value = this.value;">
<!-- Options here -->
</select>
<input type="text" id="text-input">

Categories