Jquery autocomplete combo box/selectbox using codeigniter - javascript

I want to ask, has someone ever created autocomplete using combo box / select box with code igniter?
I've tried but only managed to use autocomplete for 2 input text but I have another idea to create autocomplete with text combined with combo box. I've do created that but I have trouble my autocomplete in the text is successful but in the combo box does not work only show empty option. can someone help me? this is my source code
My Table : i probably using 2 table for autocomplete : 1. tb_produk and 2. tb_kategori_produk
https://imgur.com/a/xpysI | 2. https://imgur.com/a/DVgUl
My Controller : user.php
public function request_produk(){ //used for calling view
$data["kateprod"] = $this->db->where("f_status_kategori_produk","1")
->get("tb_kategori_produk")->result_array();
$this->theme->panel('user/v_request',$data);
}
public function mesin() //user for jquery called data
{
$keyword = $this->uri->segment(3);
$data = $this->db->from('tb_produk')->join('tb_kategori_produk','tb_kategori_produk.f_id_kategori_produk=tb_produk.f_kategori_produk')->like('f_nama_produk',$keyword)->get();
foreach($data->result() as $row)
{
$arr['query'] = $keyword;
$arr['suggestions'][] = array(
'value' =>$row->f_nama_produk,
'idpro' =>$row->f_id_produk,
'idkate' =>$row->f_id_kategori_produk,
'kategori'=>$row->f_nama_kategori_produk
);
}
echo json_encode($arr);
}
My Controller : v_request.php
<div id="content">
<script type="text/javascript">
var site = "<?php echo site_url();?>";
$(function() {
$(".autocomplete").autocomplete({
serviceUrl: site+"/user/mesin",
onSelect: function (suggestion) {
$("#v_idproduk").val(""+suggestion.idpro);
$("#v_kategori").val(""+suggestion.kategori);
$("#v_idkategori").val(""+suggestion.idkate);
}
});
});
</script>
<?php $id = $this->session->userdata('f_id_user');
<input type="hidden" name="dt[f_id_user]" value="<?php echo $this->session->userdata('f_id_user'); ?>">
<input type="hidden" id="v_idproduk" name="dt[f_id_produk]">
<input type="hidden" id="v_idkategori" name="dt[f_kategori_produk]">
<div class="form-group br-form"> <!-- This form group i used to autocomplete text -->
<div class="col-md-2">
<label class="control-label">Nama Mesin</label>
</div>
<div class="col-md-10">
<input type="search" class="autocomplete form-control" id="autocomplete1" name="nama_mesin" required/>
</div>
</div><br><br>
<div class="form-group br-form"> <!-- This form group i used to autocomplete combo box-->
<div class="col-md-2">
<label class="control-label">Kategori Mesin</label>
</div>
<div class="col-md-10">
<select id="v_kategori" name="dt[f_kategori_produk]" class="form-control" required>
<option value="">---Harap Pilih---</option>
<?php foreach ($kateprod as $key) { ?>
<option value="<?=$key['f_id_kategori_produk']?>" id="v_kategori"><?php echo $key["f_nama_kategori_produk"];?></option>
<?php } ?>
</select>
</div>
</div><br>
This is my demo
https://streamable.com/wvn25

Related

Retain ajax populated value in dropdown

I have a form where two dropdowns are kept. When the value on first is selected, ajax call is made to show related results as second dropdown list. My issue is when value is selected on second dropdown and form is submitted the second dropdown list(which is being populated on basis of first selection made in first select box) gets empty. I want to retain the value into the second dropdown selected after form submit. Can I have some insight over the same.
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">Select Level:</label>
</div>
<div class="col-md-9">
<select name="levels" class="form-control" required="" id = "level">
<?php $fnc->selectBoxsearchLevel("tbl_levels_master","id","level_title", $level_id) ; ?>
</select>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#level").change(function() {
var level_id = $(this).val();
if(level_id != "") {
$.ajax({
url:"get_units.php",
data:{l_id:level_id},
type:'POST',
success:function(response) {
//console.log (response);
var resp = $.trim(response);
$("#unit").html(resp);
}
});
} else {
$("#unit").html("<option value=''>------- Selected --------</option>");
}
});
});
</script>
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">Select Unit:</label>
</div>
<div class="col-md-9">
<select name="units" class="form-control" required="" id= "unit">
<option>------- Select --------</option>
</select>
</div>
</div>
</div>
And my get_units.php
<?php
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$level_id = $_POST['l_id'];
$sql = "select * from tbl where level=$level_id";
$res = $db->query($sql);
echo "<option value=''>------- Select --------</option>";
while($row = mysql_fetch_array($res)) {
echo "<option value='".$row['id']."'>".$row['title']."</option>";
}
?>

Dropdown Onchange and Passing JavaScript Value to PHP

Hello I have a problem on how should I send a JavaScript value to PHP.
Here is my form:
Dropdown Question from database:
fiddle code
<form action="action/survey">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Select Question</label>
<div class="col-sm-10">
<select class="form-control" id="mySelect" onchange="option()">
<?php
$sql = mysqli_query($con,"SELECT *,(SELECT GROUP_CONCAT(answer) AS `option`FROM `survey_anweroptions` WHERE survey_qID = sq.survey_qID) `option` FROM `survey_questionnaire`sq WHERE sq.survey_ID = $id");
while ($q = mysqli_fetch_array($sql)) {
?>
<option value="<?php echo $q[0]?>"><?php echo $q[2]?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label " for=""></label>
</div>
<?php
$sql = mysqli_query($con,"SELECT *,(SELECT GROUP_CONCAT(answer) AS `option`FROM `survey_anweroptions` WHERE survey_qID = sq.survey_qID) `option` FROM `survey_questionnaire`sq WHERE sq.survey_ID = 1 AND survey_qID = 1");
$d1= mysqli_fetch_array($sql);
?>
<div class="form-group">
<label class="control-label col-sm-2" for="">Question</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="" value="<?php echo $d1[2]?>">
</div>
</div>
<?php
$variable = $d1[3];
$z = 1;
$piece = explode(",", $variable);
foreach ($piece as $key => $value) {
?>
<div class="form-group">
<label class="control-label col-sm-2" for="">Option <?php echo $z?> </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="" value="<?php echo $value?>">
</div>
</div>
<?php
$z++;
}
?>
<div class="text-center">
<button type="submit" class="btn btn-default" name="">Update</button>
</div>
</form>
JavaScript:
function option(){
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
What I want is if I select 1 value on the drop-down, the value of option must be sent to a PHP variable in this query:
SELECT *, (
SELECT GROUP_CONCAT(answer) AS `option`
FROM `survey_anweroptions`
WHERE survey_qID = sq.survey_qID
) `option`
FROM `survey_questionnaire`sq
WHERE sq.survey_ID = 1
AND survey_qID = (**the value of option will go here**)
You should use name instead of id. and do print_r($_POST) to check weather post data coming or not. also you dont need javascript for this until you are using ajax to call your php script
like #Coder said you the inputs send to the server with it's name attribute not id attribute
you should change the select element to
<select class="form-control" id="mySelect" name="my_select" onchange="option()">
and retrieve it's value with
$_POST['my_select'] // if you use POST method on form submition
$_GET['my_select'] // if you use GET method on form submition
$_REQUEST['my_select'] // if you accept any method

AJAX call PHP same page and reload option values

i have an html form with a date input and a multiselect.
When loading page I load the options of the multiselect through a php function.
What i want to do is to capture onChange event of the date input with a js script and launch the php script to reload the option values of the select using the new date.
This is the php code
<?php
//DEFINE
$dateMinimumInput = "";
// Handle AJAX request for changing DateMinimumInput(start)
if(isset($_POST['ajax']) && isset($_POST["dateMinimumChanged"]) ){
echo "Inside function dateMinimumChanged: " .$_POST['dateMinimumChanged'];
$dateMinimumInput = verify_input($_POST['dateMinimumChanged']);
}
$stationList = selectStations($dateMinimumInput); ?>
This is the javascript
<script>
$(document).ready(function(){
$("#dateMinimumInput").change(function(){
//Selected value
inputValue = $(this).val();
console.log(inputValue);
$.ajax({
type: 'POST',
url: '',
data: {ajax: 1, dateMinimumChanged: inputValue},
success: function(data){
console.log('works');
console.log(data);
$('body').append(response);
},
error: function(){
alert('something went wrong');
}
});
});
});
</script>
and this is the html form
<form class="" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="dateMinimumInput" class="col-form-label col-sm-4">Date Minimum:</label>
<div class="col-sm-8">
<div class="form-group">
<input type="date" class="form-control <?php if ( $dateMinimumInputErr !== "") { echo 'is-invalid'; }?>" id="dateMinimumInput" name="dateMinimumInput" placeholder="Enter date minimum" value="<?php echo $dateMinimumInput;?>">
<div class="invalid-feedback"> <?php if ( $dateMinimumInputErr !== "") { echo 'Please, ' .$dateMinimumInputErr; } ?> </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="stationInput" class="col-form-label col-sm-4">Station:</label>
<div class="col-sm-8">
<select id="stationInput" name="stationInput[]" class="form-control" multiple>
<?php
foreach($stationList as $station){
if($station['numberofmeasurements'] == 0){
echo '<option disabled="true" value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}else{
echo '<option value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<button id="submit" name="submit" type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
The fragments of code are all from the same page.
The problem is that when I change the date, the javascript captures the event but the PHP script is not executed and the options are not reload.
Any help about what I'm doing wrong?
Thank you

How to Update/Edit data in database with AngularJS

Working on a web app , I just added the below update code and it's not working .
The summary of all the below code is :
Click a Button called update
It brings out the FORM which should contain the values of the clicked/current product.
Now when I hit save in this form it should update the database but it is not.
I am using $_GET in PHP file (update.php) to get the current Product ID.And then getting all data of that product via that ID.
PS: There is no error in console.
UPDATE CODE:
<?php
include "includes/connection.php";
switch($_GET['action']) {
case 'update_entry' :
$data = json_decode(file_get_contents("php://input"));
$index = $data->id;
$productname = $data->pname;
$company = $data->company;
$price = $data->price;
$quantity = $data->quantity;
if(isset($productname) && !empty($productname) && isset($company) && !empty($company) && isset($price) && !empty($price) && isset($quantity) && !empty($quantity)){
$query = "UPDATE `product` SET `id`='$index',`name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $index";
if(mysqli_query($con, $query)) {
return true;
} else {
echo "Error: " . $sql . "<br />" . mysqli_error($con);
}
break;
}
}
?>
Controller :
myApp.controller("updateCtrl",['$scope','$http','$routeParams','$location',function($scope,$http,$routeParams,$location){
$scope.update = function(){
var currentId = $routeParams.id;
$http.post("update.php?action=update_entry",{'id':currentId})
.then(function(data){
$location.path('/viewproduct');
});
}
}]);
HTML:
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
Update Button:
<td ng-controller="updateCtrl"><a class="btn btn-primary" href="#/updateproduct/action={{product.id}}" >Update</a></td>
Do like below
your view part
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
<td><a class="btn btn-primary" ng-click="addProductData();" >Update</a></td>
Inside your controller do like below
$scope.addProductData=function(){
var updatedata=$.param({'action':'update','productname':$scope.productname,'company':$scope.company,'price':$scope.price,'quantity':$scope.quantity,'id':currentId});
$http({
method:'POST',
url:'update.php',
data:updatedata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
alert(response.data['msg']);
},function errorCallback(response) {
alert(response.data['msg']);
});
}
your update.php file should like below.
<?php
include "includes/connection.php";
$result=array();
if(isset($_REQUEST["action"]) && $_REQUEST["action"] !=""){
if($_REQUEST["action"]=="update"){
$productname = $_POST['productname'];
$company = $_POST['company'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$id=$_POST['id'];
$query = "UPDATE `product` SET `name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $id";
if(mysqli_query($con, $query)) {
$result['msg']="updated successfully";
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg']="unable to updated";
}
echo json_encode($result);
}
}
?>
i think you may basic idea.now you can implement in your way.
Try to use ng-model="{{product.name}}}" and not the placeholder in HTML.
And in your controller pass that model:
$http.post("update.php?action=update_entry",$scope.product)
Then you should get some data in your PHP.
Have you checked your php alone to make sure that you can fetch and update data using the php without angular? I would use post as it is more friendly for retrieving and updating data.
I would also b separate your call to the php endpoint into a service (factory). I would also just pass the entire object back through to ensure that you aren't missing something unless you have a concern about bandwidth.
I would unit test php first. Then separate logic in angular. Then b step through in debug to see what's being passed from the view.
I think you should check this: https://github.com/eliarms/CustomerManagerApp
This is a simple customer management app using Angularjs and PHP. The goal of the application is to highlight a lot of the different features offered by AngularJS and demonstrate how they can be used together.

how to split checked check box, text input value

![enter image description here][1]
Here I have attached the screen shot and my question is, if I select a check box free form , I couldn't take free form inet commission and bo commission value alone.If I checked the check box, value is one means I should take value 1's inet and bo commissions. Please any one help me to solve the problem. Each check box have separate value like 1,2,etc.
Here is my code : I am working under codeigniter frame work. Here is the html code and I am fetching data from table.
Is there any possible solution to split values in jquery,
<?php
if(isset($service_list) && !empty($service_list))
{ ?>
<div class="form-group">
<label class="col-sm-3 control-label">Product Name</label>
<div class="col-sm-3" id="list_staff">
<input type="checkbox" name="check_all" class="chkSelectAll">(Click to Check all)
</div>
<div class="col-sm-2">
<label>I-net Commission</label>
</div>
<div class="col-sm-2">
<label>Bo Commission</label>
</div>
</div>
<?php
foreach($service_list as $val)
{
$ds=0;
if(isset($view_list) && !empty($view_list))
{
foreach($view_list as $val1)
{
if($val['id']==$val1['mas_pro_id'])
{
$ds=1;
}
}
}
?>
<div class="form-group">
<label class="col-sm-3 control-label"><?=$val['pro_name']?></label>
<div class="col-sm-3">
<input type="checkbox" class="check_all serve"
name="permission[<?=$val['id']?>]" value="<?=$val['id']?>" <?=($ds>0)?'checked':''?>>
</div>
<div class="col-sm-2">
<input type="text" class="int_com<?=$val['id']?>" id="inet" style="width:30px;"/>%
</div>
<div class="col-sm-2">
<input type="text" class="bo_com<?=$val['id']?>" id="bo" style="width:30px;" />%
</div>
</div>
<?php }
}
else
{
echo "<div align='center' style='margin-right:100px; color:red;'>Sorry No Data Found..!</div>";
}
?>
my script:
$('#submit').live('click',function()
{
for_loading('Loading Data Please Wait...');
var cat_id=$('.cat_id').val();
var s_cid=$('.u_sub_cat_id').val();
var chkId = '';
$('.serve:checked').each(function () {
chkId += $(this).val() + ",";
});
chkId = chkId.slice(0, -1);
$.ajax({
url:BASE_URL+"product/edit_ser",
type:'get',
data:{ cat_id:cat_id,s_cid:s_cid,chkId:chkId},
success:function(result){
$("#list_view").html(result);
//THIS IS FOR ALERT
<?php /*?>jQuery.gritter.add({
title: 'Success!',
text: 'Category Added Successfully.',
class_name: 'growl-success',
image: '<?=$theme_path?>/images/screen.png',
sticky: false,
time: ''
});<?php */?>
for_response('Data Updated Successfully...');
}
});
});
My Screen shot could be like this,
Product name A Commission B Commission
free form ck box 10 % 05%
bulk booking ck box 00 % 00%
I didn't clearly understood your question, But i suppose this you are trying to get the values of the text field when its corresponding checkbox is clicked, this too on submitting. So i have created a Fiddle.
Check here!
you have to give different id's to your html elements.
<input type="checkbox" class="check_all serve" name="permission" value="1" id="check_<?php echo $val['id']?>" />
and also
<input type="text" class="int_com_<?php echo $val['id']?> style inline" id="inet_<?php echo $val['id']?>" />
<input type="text" class="bo_com_<?php echo $val['id']?> style inline" id="bo_<?php echo $val['id']?>"/>

Categories

Resources