Can't show the query result in select option - javascript

UPDATE
I'm working with codeigniter, and i have simple select option like this:
<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv" >
<?php
$jj = "<script>var e = document.getElementById('id_barang').value;document.write(e);</script>";
$noInv = $this->modelku->select_inv($jj);
?>
<option value="" selected="selected" disabled>Pilih no inventaris</option>
<?php
foreach($noInv->result() as $inv){ ?>
<option value="<?php echo $inv->no_inv ?>">
<?php echo $inv->no_inv ?>
</option><?php }
?>
</select><br>
And this is my html element with id = id_barang:
<select name="id_barang" id="id_barang" class="form-control">
<?php $idBarang = $this->modelku->select_idBrang() ?>
<?php foreach($idBarang->result() as $idBr){ ?>
<option value="<?php echo $idBr->id_barang ?>"><?php echo $idBr->id_barang ?></option>
<?php } ?>
</select required>
select_inv function from modelku:
public function select_inv($idbrang)
{
$this->db->select("no_inv");
$this->db->from('detail_barang');
$this->db->where('kondisi', 'Ada');
$this->db->where('id_barang ', $idbrang);
$query = $this->db->get();
return $query;
}
But when i click the select option, the value from no_inv doesn't appear in my select option?
Can someone help me pls?

You can't assign a value to a PHP variable by using javascript, since they have different times for execution, and when you use the script tag, unless the browser loads it, it will be only a PHP string. I think you'll need to change this to use a PHP value for the assignment.

the problem lies in using a variable $idbrang in the manual written where clause. To use a variable change the line
$this->db->where("kondisi = 'Ada' AND id_barang = '$idbrang' ");
to
$this->db->where('kondisi', 'Ada');
$this->db->where('id_barang ', $idbrang);
more info here
note: I gave this answer before the OP was completely remodeled

You can't do this:
<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv" >
<?php
$jj = "<script>var e = document.getElementById('id_barang').value;document.write(e);</script>";
$noInv = $this->modelku->select_inv($jj);
?>
<!-- // ... -->
</select>
Because the content of your PHP $jj variable is plain text, it will not select your #id_barang value. $jj will returns exactly what you put into quotes.
One way to do what you expect is using Ajax to pass javascript values to a PHP file using POST/GET methods. Here are more details.
This : id="field_' + count + '" name="fields[]' + '" will not work too because you're using a javascript variable into HTML. You can set your select id using plain javascript into a <script> tag.

Related

Fill form with data inside in array with php

My idea is to get the complete address about the user with a select element, actually I have a variable that has all the addresses $all = (array)$this->_user->getAddressCollection(); and if i make a tiny script only to get the response, the response looks like below:
I use that variable in a foreach to get the id of the address and the addresses name:
<select class="addrs">
<?
foreach($all as $addre => $info):
?>
<option value="<?php echo $info->getIdCustomerAddress(); ?>">
<?php echo $info->getAddress1() . ' ' . $info->getAddress2() . ' - ' .
$info->getAddress3(); ?>
</option>
<?php endforeach; ?>
</select>`
Since here, I dont know how to fill a form when user select one of the addresses are display on the select

How to display a text after selecting an item name in the dropdown list, the text to be displayed is not the value of select

I wanted to display the description of an item after selecting the item name in the dropdown. I saved the values of the items with its corresponding description in an array using php. so this is my code in php (it is inside a loop):
$item_name[] = ucfirst($row['item_name']);
$desci[] = ucfirst($row['descr']);
Then I have this script (which is not working)
function updateText(val)
{
var $el = document.getElementById("adv1");
for($i=0; $i < <?php echo $ctr ?>; $i++)
{
if(val == '<?php echo "'.$itemid[$i].'" ?>')
{
$el.value = "$ 750";
}
else
{
$el.value = "0";
}
}
}
and here is my html code
<select name="item" id="datetime" onchange="updateText(this.value)" autofocus required>';
for ($i=0; $i < $ctr; $i++) {
echo ' <option value="'.$itemid[$i].'">'.$item_name[$i].' '.$brand[$i].' </option>';
}
echo '</select><p id="adv1"> </p>';
I was wondering how to retrieve the data from php and use it in javascript. Sorry, newbie here. Any help is appreciated, TIA!
<?php
echo '<select name="item" id="datetime" onchange="updateText(this.options[this.selectedIndex].getAttribute(\'data-val\'))" autofocus required>';
for ($i=0; $i <$ctr; $i++) {
echo ' <option value="'.$itemid[$i].'" data-val="'.$desci[$i].'">'.$item_name[$i].' '.$brand[$i].' </option>';
}
echo '</select><p id="adv1"> </p>';
?>
<script>
function updateText(nttest){
document.getElementById("adv1").innerHTML=nttest;
}
</script>
hope it will help, In data-val you can pass value what you need to display in adv1
You need to use ajax , ajax is simple to use , just follow the example on this link , it just refreshes the div so you don't have to refresh the entire page just to display something
http://www.w3schools.com/ajax/

passing two variable from php to ajax then back to php

I'm new to ajax so I don't know much about ajax syntax. though i am trying here to pass variable from php to ajax and then back to php. I was able able to get it done with one variable when it came to two variables I was confused. I don't even know what to search on google to get an answer my to query. So I will be brief here's my php code. addnewbug.php
<script type="text/javascript" language="javascript" src="./javascripts/jquery.js"></script>
<script type="text/javascript" language="javascript" src="./javascripts/script.js"></script>
</head>
<div class="margin custom">
<body bgcolor="#2e2e2e">
<div style="text-align: center; padding-top: 0px">
<h1 style="color:white;font-size: 50px">Bughound</h1>
</div>
<div class="effect8">
<div class="tableMargin">
<table width="622" class="table">
<tr class="program_row">
<form>
<td width="150" class="td" style="padding-right: 1.9cm">Program</td>
<td width="171" class="td">
<select id="program" class="dropdown">
<option></option>
<?php
require "./db.php";
$sql = "SELECT DISTINCT program_name FROM program";
$result = db($sql);
while ($row = $result->fetch_assoc()) {
$program_name = $row['program_name'];
echo '<option name ="' . $program_name . '">' . $program_name . '</option>';
}
?>
</select>
</td>
<td width="51" class="td">Release</td>
<td width="41" >
<div class="release" id="release">
<select class="release_select" id='release1'>
</select>
</div>
</td>
<td width="103" class="td">Version</td>
<td width="78" class="td">
<div class="version" id="version">
<select class="version_select" id='program_number'>
</select>
</div>
</td>
</form>
</tr>
</table>
This is the original page where I'm trying to make changes in select box using the get passing statement
here's the script.js which I am using to get variable and pass it to another php program..
$(function(){
$("#program").change(function(){
$(".release_select").remove();
$(".version_select").remove();
if($("#program").val() !== "") {
$.get("addnewbug1.php", {program_name: $("#program").val()})
.done(function(data){
$("div.release").after(data);
});
$.get("addnewbug_version.php", {program_name: $("#program").val()})
.done(function(data){
$("div.version").after(data);
});
}
});
$("#program_number").change(function(){
$(".release_select").remove();
if($("#program_number").val() !== "") {
var val2 = $("#program_number").val();
$.get("addnewbug2.php?program_number="+val2, {program_name: $("#program").val()})
.done(function(data){
$("div.release").after(data);
});
}
});
});
The first function is working fine as it takes values from the program and pass it to addnewbug1.php which takes the program name and generate the new select boxes for release and version of it then which is replaced in div-release and division-version(or number)
this is the file where the first function work perfectly - addnewbug1.php
require "./db.php";
echo "<select class='release_select' id='release1'>";
$programname = $_GET['program_name'];
$sql1 = 'SELECT DISTINCT program_release FROM program WHERE program_name="'. $programname .'"';
$result1 = db($sql1);
while ($row1 = $result1->fetch_assoc()) {
$program_release = $row1['program_release'];
echo '<option name ="' . $program_release . '">' . $program_release . '</option>';
}
echo "</select>";
?>
Now I am having error in the second change function of script.js where I need to pass two variables in '$.get' area. Also the .change fucntion for program_number is not working and it won't delete the select box on changing it.
$.get("addnewbug2.php?program_number="+val2, {program_name: $("#program").val()})
and the addnewbug2.php is also the new file which is being used by it is -
require "./db.php";
echo "<select class='release_select' id='release1'><option></option>";
$programname = $_GET['program_name'];
$programnumber = $_GET['program_number'];
$sql1 = 'SELECT DISTINCT program_release FROM program WHERE program_name="'. $programname .'" and program_number=' . $programnumber;
$result1 = db($sql1);
while ($row1 = $result1->fetch_assoc()) {
$program_release = $row1['program_release'];
echo '<option name ="' . $program_release . '">' . $program_release . '</option>';
}
echo "</select>";
?>
I don't know if you get my question or not. Thank you for replying to this question and please reply if require more info.
this is the addidtional db.php code
function db($sql){
//Check for connection variable already set
if(!isset($conn)){
//Database Connectivity - ip, username, password, database name
$conn = new mysqli("i have filled this correctly");
}
//Check Connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, $sql);
mysqli_close($conn);
return($result);
}
If I get that correctly, your initial problem is to pass more than one variable in AJAX call.
You can construct the URL like this :
var val2 = $("#program_number").val();
var val1 = $("#program").val();
$.get("addnewbug2.php?program_number="+val2+"&program_name="+val1)
json_encode() is perfect for transport php variable with ajax
something like
//your ajax call receiver page -: your_link_for_ajax.php
$output = json_encode(array('type'=>'success','address'=>$address,'table_record'=>$table_record));
die($output);
you can read it like
this code on your html page
$.post('your_link_for_ajax', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="alert alert-danger">'+response.text+'</div>';
}else{
output = '<div class=" alert alert-success">'+response.address+'</div>';
$('#stateIdContact').html(response.table_record);
}
}, 'json');
Thank you for replying, i solved my problem using AngularJS, which i started reading after posting this question. My main moto behind this question was to populate a (2nd)select box and (3rd)select box using value from other (1st) select box and when the values in newly populate (2nd) select box was done. Then change values (3rd)select box using the (2nd) select box. Vice versa for last point. Apply unique filter to select boxes and without moving to next page.
So here's the code simplified form of Addnewbug.php-
<!DOCTYPE html>
<html >
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.4/angular-filter.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<select ng-model="selectProgram">
<option></option>
<option ng-repeat="x in programes | unique: 'prognumber'" name=""{{x.progname}}"">{{ x.progname }}</option>
</select>
<select ng-model="selectNumber">
<option></option>
<option ng-repeat="x in programes | filterBy: ['progname']:selectProgram | filterBy: ['progrelease']:selectRelease | unique: 'prognumber'" name=""{{x.prognumber}}"">{{ x.prognumber }}</option>
</select>
<select ng-model="selectRelease">
<option></option>
<option ng-repeat="x in programes | filterBy: ['progname']:selectProgram | filterBy: ['prognumber']:selectNumber | unique: 'progrelease'" name=""{{x.progrelease}}"">{{ x.progrelease }}</option>
</select>
</div>
<script>
var app = angular.module('myApp', ['angular.filter']);
app.controller('customersCtrl', function($scope, $http) {
$http.get("db/program_db.php")
.success(function (response) {$scope.programes = response.records;});
});
</script>
</body>
</html>
offcourse i used some other stackexchange questions to get it right.
And for the table which is being imported in this code i used this program_db-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if(!isset($conn)){
//Database Connectivity - ip, username, password, database name
$conn = new mysqli("*connection parameters*");
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, "SELECT program_name, program_number,program_release FROM program");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"progname":"' . $rs["program_name"] . '",';
$outp .= '"prognumber":"' . $rs["program_number"] . '",';
$outp .= '"progrelease":"'. $rs["program_release"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
I have same problem as you had in this page: PHP ajax database : how to pass two variables and get data of them in different options? ,i have 2 diffrent php file,one is handling select files,the other handle the database sql,firstly i pass a value which user choosed from first select which updates the second select,and choosing second select should update third select(which is remain empty) i dont know what is my problem(i guess i send value of first ajax to the other php file,and when i get it back to use it for second ajax call,the first value will gone.

how manage auto-submit with the action atribute in the form

I needed make a dinamic dependent dropdown in a form,so i found this solution that uses the JS auto-submit function:
function autoSubmit()
{
var formObject = document.forms['dados'];
formObject.submit();
}
then I use the onchange event in the first dropdown to call the auto-submit function:
<label>Campus:</label>
<select name="campus" onchange="autoSubmit();">
<option VALUE="null"></option>
<?php
//Popula a lista com os cursos do DB
$sql = "SELECT id,nome FROM campus";
$countries = mysql_query($sql,$conn);
while($row = mysql_fetch_array($countries))
{
if($row[nome]==$campus)
echo ("<option VALUE=\"$row[nome]\" selected>$row[nome]</option>");
else
echo ("<option VALUE=\"$row[nome]\">$row[nome]</option>");
}
?>
</select>
with this the element "campus" will be setted to be used in the second dropdown SELECT statement:
$campus = $_POST['campus'];
...
<label>Curso:
<span class="small">curso corrente</span>
</label>
<select name="curso">
<option VALUE="null"></option>
<?php
$consulta2 = "SELECT curso FROM campus_cursos WHERE campus = \"" . $campus . "\"";
$cursoslista = mysql_query($consulta2,$conn);
while($row = mysql_fetch_array($cursoslista))
{
echo ("<option VALUE=\"$row[curso]\">$row[curso]</option>");
}
?>
</select>
this code is working,but the problem is that in this way I cant set a action atribute in the form because if i do this every time the first dropdown changes it will redirect to the action's URL.this is the form that works:
<form name="dados" method="POST" onsubmit="return validar();">
with no action atribute I cant use a submit button to send the data of all the others elements to the right URL.there is a way to this?
You should use Ajax code to populate the second dropdown values.
On Form's page:
<label>Campus:</label>
<select name="campus" id="campus">
<option VALUE="null"></option>
<?php
//Popula a lista com os cursos do DB
$sql = "SELECT id,nome FROM campus";
$countries = mysql_query($sql,$conn);
while($row = mysql_fetch_array($countries))
{
if($row[nome]==$campus)
echo ("<option VALUE=\"$row[nome]\" selected>$row[nome]</option>");
else
echo ("<option VALUE=\"$row[nome]\">$row[nome]</option>");
}
?>
</select>
<label>Curso:
<span class="small">curso corrente</span>
</label>
<select name="curso" id="curso">
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#campus').change(function(){
var campusName = $(this).val();
$('#curso').load('generateCurso.php?campus='+campusName);
});
});
</script>
Write a PHP file, called generateCurso.php
<?php
$campus = $_GET['campus'];
$consulta2 = "SELECT curso FROM campus_cursos WHERE campus = \"" . $campus . "\"";
$cursoslista = mysql_query($consulta2,$conn);
?>
<option VALUE="null"></option>
<?php
while($row = mysql_fetch_array($cursoslista))
{
echo ("<option VALUE=\"$row[curso]\">$row[curso]</option>");
}
?>
I solved this issue using a ajax script triggered by "on change" event.the ajax script call a external file that return an array of elements.the script use these elements to populate the dropdown list.

How to use Javascript or Jquery to switch the select elements?

I don't know much about Javascript and Jquery, but I do have to use it on a HTML select tags. I have two database tables, grouptypes and groups. A grouptype can have multiple groups, but a group only belongs to one grouptype. I have two select tags, one is grouptypes and another one is groups. What I want to do is that whenever a user select a grouptype in the grouptypes dropdown menu, it triggers a handler to retrieve the corresponding groups that belong to that grouptype. I need javascript or Jquery to get it done, but I am not able to write it myself. So anyone can help me? I would so appreciate it.
GroupType: <select name="groupType">
<?php foreach($grouptypes as $type) : ?>
<?php echo "<option value='" . $type['name'] . "'>" .$type['name']. "</option>"; ?>
<?php endforeach ?>
</select><br />
Group: <select name="groups">
<?php foreach($groups as $group) : ?>
<?php echo "<option value='" . $group['name'] . "'>" .$group['name']. "</option>"; ?>
<?php endforeach ?>
</select><br />
<?php
$query = "SELECT id, name FROM group_type";
$grouptypes = $_db->getResultsForquery($query);
$query = "SELECT id, name FROM groups";
$groups = $_db->getResultsForquery($query);
?>
Here's what I would do. It uses jquery to send a get to a page called groups.php which will return some html you can parse. Then you parse it :)
$('#grouptype-select').change(function(){ //.change will detect when the select has been changed (an -option- has been chosen)
var grouptype = $(this).val(); //create a variable from the -option- chosen
$.get('groups.php', 'grouptype=' + grouptype, function(response){ //use jquery to send -get- to groups.php
$('#list-of-groups').html(response); //insert response into ur doc
}
});
Something like http://www.yoursite.com?grouptype=abc will be sent using get asynchronously (ajax) Good luck!
PS Here is a jsfiddle to get you tinkering: http://jsfiddle.net/yLyTw/1/

Categories

Resources