I'm trying to add a value from a selected in my html into a PHP file using jQuery. I have 2 php file, chainmenu.php and function.php. function.php contain 2 functions to get some data from my database. chainmenu.php is used to show the result of a function from function.php. It requires a variable, that is a value from selected option in my html. I was able to retrieve the value, but my problem is that my $.post function doesn't work. I dont know where is the error, is it in my chainmenu.php or in my function.php.
This is my code
jQuery CODE
<script type="text/javascript">
$(document).ready(function() {
$("select#trafo").attr("disabled","disabled");
$("select#gi").change(function(){
$("select#trafo").attr("disabled","disabled");
$("select#trafo").html("<option>wait...</option>");
var id = $("select#gi option:selected").attr('value');
$("select#trafo").html("<Option>"+id+"</Option>");
$.post("chainmenu.php", {id:id}, function(data){
$("select#trafo").removeAttr("disabled");
$("select#trafo").html(data);
});
});
});
</script>
Function.php
<?php class SelectList
{
//$this->conn is working fine here
public function ShowGI()
{
$sql = "SELECT * FROM gi";
$res = mysqli_query($this->conn,$sql);
if(mysqli_num_rows($res)>=1){
$category = '<option value="0">Pilih GI</option>';
while($row = mysqli_fetch_array($res))
{
$category .= '<option value="' . $row['idgi'] . '">' . $row['namegi'] . '</option>';
}
}
return $category;
}
public function ShowIt()
{
$sql = "SELECT * FROM It WHERE idgi=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">Choose/option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['idIt'] . '">' . $row['name'] . '</option>';
}
return $type;
}
}
$opt = new SelectList();
?>
chainmenu.php
<?php include "/opsi.class.php";
echo $opt->ShowIt(); ?>
HTML Code
<head>
<!-- the script here -->
</head>
<body>
<select id=gi>
<option value="0"> Select </option>
</select>
<select id=It>
<!-- chainmenu.php result should be here -->
</select>
</body>
This explanation a little bit messy, but i hope anyone could help me and give me some good advice.
Thank you.
try like this in chainmenu.php
<?php include "/opsi.class.php";
echo $opt->ShowIt($_POST['id']); ?>
in function.php replace ShowIt() method like below,
public function ShowIt($id)
{
$sql = "SELECT * FROM It WHERE idgi=$id";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">Choose/option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['idIt'] . '">' . $row['name'] . '</option>';
}
return $type;
}
There are a few typos in ShowIt() function for e.g $type = '<option value="0">Choose/option>'; the tag isn't closed properly.
In the jquery code you are retrieving the value and adding the html to select tag having id trafo. whereas in html code the id of the select is It.
<select id=It>
<!-- chainmenu.php result should be here -->
</select>
Related
I am trying to learn php and now I am stucked with one thing.
I have the code like this:
<select name = "Option1" id ="Option1">
<option value="0">Option1</option>
<?php
include ("db_connect.php");
$option1 = $pdo->query("SELECT * FROM options");
while($row = $option1->fetch(PDO::FETCH_ASSOC)){
echo '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
}
?>
</select>
Which is select element with options from database.
But I need 5 of them and copying this piece of code 5 times just doesn't make sense, or am I wrong?
I tried something like this:
function renderSelect()
{
for ($a = 0; $a < 5; $a++){
echo '<select>
<option value="0">Option ' . $a . '</option>
' . renderOptions($a) . '
</select>';
}
}
function renderOptions(){
include ("db_connect.php");
$option1 = $pdo->query("SELECT * FROM options");
while($row = $option1->fetch(PDO::FETCH_ASSOC)){
echo '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
}
}
And then just call the renderSelect, but it's not working how expected.
Can you please give me little advice what to do here?
Thanks a lot I appreciate it!
Try to use return in your second function. If you echo it in the second function, it will add the echo output to the beginning, where you called the function. You create a String, where you add all your options to it and then return that string.
function renderOptions(){
include ("db_connect.php");
$option1 = $pdo->query("SELECT * FROM options");
$string = "";
while($row = $option1->fetch(PDO::FETCH_ASSOC)){
$string .= '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
}
return $string;
}
And another point to mention, you are calling renderOption function and passing $a to a function, which takes to parameter.
My code works properly, it is display all messages and entry dates. I want to display message and entry date when I select customer name from drop down list.
Here is my controller CustomerlifecycleController
public function actionCustomerlifecycleanalytic() {
$customername = Customer::model()->findall("store_id='" . Yii::app()->session['store_id'] . "'");
$customerlifecycle = CustomerLifecycle::model()->findAll();
$this->renderPartial('customerlifecycleanalytic', array( 'customername' => $customername, 'customerlifecycle' => $customerlifecycle), false, true);
}
Here is my view file customerlifecycleanalytic.php
Dropdown list
Customer name fetch from customer model
and there is column name id for customer
<select class="form-control selectpicker customerfilter">
<option value=''>Select Customer</option>
<?php
if (isset($customername)) {
foreach ($customername as $customernames) {
echo '<option value="' . $customernames['id'] . '" >' . $customernames['firstname'].' '. $customernames['lastname']. '</option>';
}
}
?>
</select>
Message and entry date fetch from Customerlifecycle model there is column name is customer_id
$msg = '<li {classstr}>
<div class="tl-circ">
</div>
<div class="timeline-panel">
<div class="tl-body">
<p>
{msg} on {date}</p>
</div>
</div>
</li>';
$cnt = 0;
$htmlstring = '';
foreach ($customerlifecycle as $key => $row) {
$htmlstring .= $msg;
$classString ='';
if ($cnt % 2 == 0) {
$classString = " class='timeline-inverted' ";
}
$htmlstring = str_replace("{classstr}", "$classString", $htmlstring);
$htmlstring = str_replace("{msg}", "$row->message", $htmlstring);
$htmlstring = str_replace("{date}", "$row->entrydate", $htmlstring);
$cnt++;
}
echo $htmlstring;
?>
My code is already running completely but I want when I select customer name form drop down list at that time it will display only that customer's message and entry date.
To display selected customer's message and entry date, you can call javascript function on onChange event of dropdownlist as follows:
<script type="text/javascript" language="Javascript">
function submitForm() {
document.getElementById("form-id").submit();
}
</script>
<select class="form-control selectpicker customerfilter" name="Customer[id]" onChange="js: return submitForm();">
Using this javascript function, submit the form and make changes in your controller as follows:
public function actionCustomerlifecycleanalytic() {
$customername = Customer::model()->findall("store_id='" . Yii::app()->session['store_id'] . "'");
$strCondition = "";
if(isset($_POST['Customer'])) {
if (!empty($_POST['Customer']['id'])) {
$strCondition .= "store_id = '" . Yii::app()->session['store_id'] . "' AND customer_id = '" . $_POST['Customer']['id'] . "'";
}
}
$customerlifecycle = CustomerLifecycle::model()->findAll($strCondition);
$this->renderPartial('customerlifecycleanalytic', array( 'customername' => $customername, 'customerlifecycle' => $customerlifecycle), false, true);
}
Hope this helps!
I'm having a little trouble with my code and I'm hoping someone can help. I'm trying to have the user select an option from a select box and then another select box to be based on that queries result. I know this should be simple but I can't seem to get it to work. Here's the code I've got so far.
The First select box:
select id="selCategory" name="category" class="chzn-select"<?php if (in_array('category',$_SESSION['iserror'])) {echo ' class="isError" ';} ?> >
<option value ="" ">
<?php
while ($row = hesk_dbFetchAssoc($res))
{
echo '<option value="' . $row['id'] . '"' . (($_SESSION['c_category'] == $row['id']) ? ' "' : '') . '>' . $row['name'] . '</option>';
}
?>
</select>
The second select box:
<select id="selAsset" name ="asset" class="chzn-select">
<option value="" selected="selected"></option>
<?php
while ($row = odbc_fetch_array($Assets))
{
echo '<option value="' . $row['AssetID'] . '"' . (($_SESSION['c_asset'] == $row['AssetID']) ? ' selected="selected"' : '')
. '>' . $row['AssetName']. '</option>';
}
odbc_close($conLansweeper);
?>
</select>
The code to handle if the second drop down box is displayed.
<script language="Javascript" type="text/javascript">$(function()
{
$(".selCategory").chosen().change(function(){
var selectedCategory=$(this).find("option:selected").val();
if(selectedCategory == "1")
{
$(.selAsset).show();
}
else
{
$(.selAsset).hide();
}
});
});
</script>
Footer Code:
<script type="text/javascript" src="script/chosen/jquery.min.js"></script>
<script type="text/javascript" src="script/chosen/chosen.jquery.js"></script>
<!--<script type="text/javascript" src="script/jquery/jquery-1.10.2.min.js"></script>-->
<script type="text/javascript">$(".chzn-select").chosen({disable_search_threshold: 10, width:200, placeholder_text_single:" ", search_contains: true, allow_single_deselect: true });</script>
The basic aim is for the second select box to be hidden when the page loads and the display when the appropriate value is selected in the first select box.
Can anyone help me out? I've not managed to get this working before and If i can get a working example and some help to show where I'm going wrong would really help.
Approach 1 (using existing html):
Hide with css:
#selAsset {
display:none;
}
Then jQuery:
$(function(){
var selCategory = $('#selCategory');
$(selCategory).change(function() {
$('option:selected').each(function() {
if($(this).text() === '3') {
jQuery('#selAsset').show();
}
});
});
});
This uses text() to check the selected option. In your code there is no need for .chosen() and you can change this: $(.selAsset).show(); to this: $('#selAsset').show(); (to match the html).
Demo: http://jsfiddle.net/dRM92/1/
A better approach (from comments):
We can use .change(function(){ and a switch case to check the option's value; then manipulate accordingly.
var selCategory = $('#selCategory');
var selAsset = $('#selAsset');
selCategory.change(function() {
switch ($(this, 'option:selected').val()) {
case "3":
selAsset.show();
break;
case "please select":
selAsset.hide();
break;
}
});
This is more extendable than the previous approach. There are many ways to check an option's value or text; for this instance we need to check the selected value only and the argument/s you wish to have.
Demo: http://jsfiddle.net/gzWGQ/1/
I am pulling out record from the database and inserting them inside a dropdown like this:
echo "<select>";
while ($drow = mysql_fetch_assoc($request))
{
echo "<option>" . $drow['id'] . "</option>";
}
echo "</select>";
It works but I need to be able to click on an option on the dropdown and make it link just like:
Record1Here
Record2Here
Record3Here
UPDATE: Latest code:
<script>
function doSomething() {
var currentval = this.options[this.selectedIndex].value;
// you could navigate away at that point ?
window.location = currentval;
}
</script>
...
echo "<select onchange='doSomething();'>";
while ($drow = mysql_fetch_assoc($request))
{
echo "<option value=\"view.php\">" . $drow['id'] . "</option>";
}
echo "</select>";
You can't place anchors on an option within a select list.
What you can do is use JavaScript and then do something on the change event of the select list :
echo "<select onchange='doSomething(this);>';
then in JavaScript do something based on the selected value :
function doSomething(elem) {
var currentval = elem.options[elem.selectedIndex].value;
// you could navigate away at that point ?
window.location = currentval;
}
Example here
you could update your PHP code to include a value in each option :
echo "<option value=\"urlhere.php\">" . $drow['id'] . "</option>";
I have this script:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
$('.filterMonth').change(function(){
alert('ijijiji');
$.ajax({
url: 'ajax/filterMandays.php',
//type: 'GET',
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});
</script>
and this html:
<select name ="filterMonth">
<?php
$array_month = array("January","February","March","April","May","June","July","August","September","October","November","December");
foreach($array_month as $key => $month)
{
$value_month = $key+1;
echo "<option value = '$value_month'>$month</option>";
}
?>
</select>
-
<select name = "filterYear" onChange = "filter(filterMonth.value, filterYear.value)">
<?php
$curYear = date('Y');
for($i = 1990; $i<=$curYear+10; $i++)
{
if($i == $curYear)
{
echo "<option value = '$i' selected = 'selected'>$i</option>";
}
else
{
echo "<option value = '$i'>$i</option>";
}
}
?>
</select>
</td>
</tr>
</br>
</br>
<tr>
<div id="mandayTable"></div>
and this php page:
<?php
include("all.php");
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';";
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
while($rows = $res->FetchRow())
//for($i=0;$i<5;$i++)
{
//iterating through // check if employee
// // if(isset($row[])) { }
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows['month'];
$lastname = $rows[6];
//echo approvers here are not taken
//<a href=\"view_team.php?id=".$empnum."\" -> for someone to view the people beneath them (like org tree)
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
the script should basically load the php page in the div in the html once the "filterMonth" has been changed. but it doesn't work.
what seems to be the problem? :(
The selector in your jQuery is $('.filterMonth') but your select box doesn't have the filterMonth class. You need to change it to $('select[name=filterMonth]').
In order for the jQuery selector to contain your select, you need to make sure that it runs after the Select element is in the DOM (ie: lower down the HTML), or run your JavaScript once the document has finished loading, for example:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
jQuery(function() {
// do your DOM selections here, this function only runs once the document is loaded
});
</script>