I have trawled the net for sometime now trying to find a solution which cold assist me, but have had no luck.
I have a simple sales form in which the user selects a product from a drop down list. on selecting a value, I want the input box value to get passed to a database query, and the query result (price) be displayed on the form. if possible I want the result to populate an input box so the salesman can adjust as needed.
I am using codeigniter which makes finding a good example quite difficult.
Controller
function new_blank_order_lines()
{
$this->load->view('sales/new_blank_order_lines');
}
Model
function get_sku_price($q){
$this->db->select('ProductPrice');
$this->db->where('ProductCode', $q);
$query = $this->db->get('ProductList');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['ProductPrice'])); //build an array
}
$this->output->set_content_type('application/json')->set_output(json_encode($row_set));
}
}
View
<table>
<tr><td>Product</td><td>Price</td></tr>
<tr>
<td><select name="product">
<option="sku1">product 1</option>
<option="sku2">product 2</option>
<option="sku3">product 3</option>
<select></td>
<td><input type="text" id="price" name="price" /></td>
</tr>
</table>
I have loaded the jquery library, 1.9.1.
I have got autocomplete working but the sytax is just not the same.
So what I am wanting, is that when I select a product code from the product drop down list, the value is passed to the model, the query result(price) is then displayed in the input box price.
Can anyone provide some insight on how to do this, or a good working example?
Thanks a million, this community is awesome!
Fabio
Controller:
function new_blank_order_lines()
{
$this->load->view('sales/new_order');
}
The view:
<script>
$("#product").change(function () {
//get the value of the select when it changes
var value = $("#product").val()
//make an ajax request posting it to your controller
$.post('<?=base_url("sales/get_sku_prices")?>', {data:value},function(result) {
//change the input price with the returned value
$('#price').value(result);
});
});
</script>
<table>
<tr><td>Product</td><td>Price</td></tr>
<tr>
<td><select name="product" id="product">
<option value="sku1">product 1</option>
<option value="sku2">product 2</option>
<option value="sku3">product 3</option>
</select></td>
<td><input type="text" id="price" name="price" /></td>
</tr>
</table>
Controller to fetch database data:
function get_sku_prices(){
//check if is an ajax request
if($this->input->is_ajax_request()){
//checks if the variable data exists on the posted data
if($this->input->post('data')){
$this->load->model('Sales_model');
//query in your model you should verify if the data passed is legit before querying
$price = $this->your_model->get_sku_price($this->input->post('data', TRUE));
echo $price;
}
}
}
Model:
function get_sku_price($q){
$this->db->select('ProductPrice');
$this->db->where('ProductCode', $q);
$query = $this->db->get('ProductList');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['ProductPrice'])); //build an array
}
$this->output->set_content_type('application/json')->set_output(json_encode($row_set));
}
}
Your View:
<table>
<tr>
<td>Product</td>
<td>Price</td>
</tr>
<tr>
<td>
<select name="product" id="product">
<option value="sku1">product 1</option>
<option value="sku2">product 2</option>
<option value="sku3">product 3</option>
</select>
</td>
<td>
<input type="text" id="price" name="price" />
</td>
</tr>
</table>
The javascript
<script>
$("#product").change(function () {
//get the value of the select when it changes
var value = $("#product").val()
//make an ajax request posting it to your controller
$.post('<?=site_url("controller/function")?>', {data:value},function(result) {
//change the input price with the returned value
$('#price').value(result);
});
});
</script>
The controller:
public function your_funtion(){
//check if is an ajax request
if($this->input->is_ajax_request()){
//checks if the variable data exists on the posted data
if($this->input->post('data')){
$this->load_model('your_model')
//query in your model you should verify if the data passed is legit before querying
$price = $this->your_model->get_price($this->input->post('data', TRUE));
echo $price;
}
}
}
use jquery's ajax,post or get and change event..using post here
example..
$('select[name="product"]').change(function(){
var val=$(this).val();
$.post('path/to/controller',{data:val},function(result){
$('#price').val(result.price);
}, "json");
});
conroller funciton
$product=$this->input->post('data'); //this will give you the selected value of select
//make query to db in model..get price and
$price = ..//price that you got from db
echo json_encode(array('price'=> $price));
Related
I'm trying to make a dynamic dropdown with Codeigniter but I'm having trouble getting the values on the next dropdown. When I select and option on the first dropdown, the second dropdown is not populated:
I'm also not familiar at using AJAX, I only write the script based on what I searched so please teach me what to do to make the dynamic dropdown work.
This is my Model:
public function category()
{
$this->db->order_by("category", "ASC");
$query = $this->db->get('categories');
return $query->result();
}
function get_subcategory($parent_id)
{
$this->db->where('parent_id', $parent_id);
$this->db->order_by('sub_category', 'ASC');
$query = $this->db->get('sub_categories');
$output = '<option value="">Select Sub-Category</option>';
foreach ($query->result() as $row) {
$output .= '<option value="' . $row['id'] . '">' . $row['sub_category'] . '</option>';
}
return $output;
}
My Controller:
public function category()
{
$data['title'] = 'List of Category';
$this->load->view('../admin/template/admin_header');
$this->load->view('../admin/template/admin_topnav');
$this->load->view('../admin/template/admin_sidebar');
$this->load->view('../admin/category/category', $data);
$this->load->view('../admin/template/admin_footer');
}
function get_subcategory()
{
if ($this->input->post('parent_id')) {
echo $this->Admin_model->get_subcategory($this->input->post('parent_id'));
}
}
View:
<div class="form-group">
<label for="" class="control-label">Category</label>
<select name="category" id="category" class="custom-select select2" required>
<option value="">- Select Category -</option>
<?php
foreach ($category as $row) {
echo '<option value="' . $row->id. '">' . $row->category . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="" class="control-label">Sub Category</label>
<select name="sub_category" id="sub_category_id" class="custom-select select2" required>
<option value="">- Select Sub Category -</option>
</select>
</div>
And script:
$(document).ready(function() {
$('#category').change(function() {
var parent_id = $('#category').val();
if (parent_id != '') {
$.ajax({
url: "<?php echo base_url(); ?>admin/get_subcategory",
method: "POST",
data: {parent_id:parent_id},
success: function(data) {
$('#sub_category_id').html(data);
}
});
} else {
$('#sub_category_id').html('<option value="">Select Sub Category</option>');
}
});
});
Your question doesn't mention it, but your CSS suggests your selects are actually using Select2. When you initialise a select as a Select2, it makes a copy of the initial HTML, and adds styling and JS to it, and it is the copy that you see and interact with. The original HTML is no longer visible or used at all.
So if you later come along and modify that original HTML, it will have no effect on the Select2 you already generated and can see an interact with on the page.
One solution is to reinitialise that Select2 after you modify it.
UPDATE
I've added a working snippet, with some hard-coded HTML to simulate what your AJAX returns. Click run to try it.
$(document).ready(function () {
// Initialise Select2s
$('.select2').select2();
// Fake HTML, simulate what your AJAX returns
let fakedHTMLResponse = '<option value="water">Water</option><option value="juice">Juice</option><option value="beer">Beer</option>';
$('#category').change(function () {
var parent_id = $('#category').val();
// console.log('parent_id', parent_id);
if (parent_id != '') {
// Your AJAX call happens here, let's simulate the success
// response it gets back, and handle it the same way.
$('#sub_category_id').select2('destroy')
.html(fakedHTMLResponse)
.select2();
} else {
$('#sub_category_id').html('<option value="">Select Sub Category</option>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="category" class="select2" name="food">
<option value="">- Select Category -</option>
<option value="fruits">Fruits</option>
<option value="vegetables">Vegetables</option>
<option value="cakes">Cakes</option>
</select>
<select id="sub_category_id" class="select2" name="drink">
<option value="">- Select Sub Category -</option>
</select>
Note:
Convention is to use GET when retrieving data, and POST for changing data. Your AJAX calls are just retrieving data to display, so really should be GET;
If you are going to use a jQuery selector more than once, it makes sense to cache them. Eg in the above code you should do something like:
let $category = $('#category');
let $sub = $('#sub_category_id');
// And then every time you need to use that selectors, use the variable, eg:
$category.select2();
$category.change(function ...
$sub.select2('destroy');
// etc
In your success response write this and remove the else from down there.
success: function(data) {
$('#sub_category_id').append('<option value=>Select Sub Category</option>');
for (var i=0; i<data.length; i++) {
$('#sub_category_id').append($('<option>', {
value: data[i].id,
text : data[i].sub_category
}));
}
}
get AJAX response in the array from your controller and then run this through javascript like this.
id is id from your db
and sub_category is sub_category coming from your db
with ajax response array.
I have select2 field input. After using select2 its will showing new column and data from this input selected.
I have referenced like this link. So after I using select2, this value will show in a new column. But I don't know how to catch this data. I am using Laravel and this is my controller and view:
Controller
$collection = Alat::get(['nama_alat','no_inventaris','status_alat','id']);
foreach ($collection as $item) {
$inven[$item->id] = $item->no_inventaris.'-'.$item->nama_alat;
}
This is will shown in columns no_inventaris and nama_alat in the select2. But in the $collection, I have status_alat, this data is what I need to display in another column.
This is my view:
// This is form Select2
<div class="form-group">
<label>Pilih Inventaris</label>
<select class="form-control select2bs4" name="alat_id" id="alat_id" style="width: 100%;" aria-hidden="true" onchange="Show()">
<option value=""></option>
#foreach($inven as $id => $item )
<option value="{{ $id }}">{{ $item }} </option>
#endforeach
</select>
</div>
// This is form what i need to show another value
<div class="form-group" id="divid" style="display:none">
<label class="control-label" for="title">Kondisi Alat Sekarang:</label>
<input type="text" name="" class="form-control" id="value" data-error="Please enter title." readonly />
<div class="help-block with-errors"></div>
</div>
Here's my Javascript:
<script>
function Show()
{
var fieldValue = $('#alat_id').val();
if(fieldValue == "")
{
document.getElementById("divid").style.display = 'none';
}
else{
document.getElementById("divid").style.display = 'inline'
}
}
</script>
This data I need to catch in the controller $collection as status_alat. How can I catch this data after input the select2 and showing in the new column? This column is shown, but I don't know how to catch this data. Sorry for my bad English
The best solution should be using ajax, it is quite complicated to access a PHP collection variable inside a javascript. If it were me, I would create a function that fetch the selected select2 data by its id. This is my example code :
<script>
function select2Changed()
{
var alat_id = $('#alat_id').val();
if(fieldValue == ""){
document.getElementById("divid").style.display = 'none';
} else{
document.getElementById("divid").style.display = 'inline';
$.ajax({url: "[url]/get-alat-status/"+alat_id, success: function(result){
document.getElementById("value").value = result;
}});
}
}
</script>
I have multiple selects in a table and I want to be able to change the options of al the selects on a column when I change the option of the select on the first row. The problem is that the selects are added dynamically. I managed to do this by targeting the first select of each column by it's ID, but I'm looking for a way to do this for all elements at once.
This is the code I have for each column:
$('id-of-the-table-that-already-exists-on-page').on('change','id-of-the-first-select-on-each-column', function() {
var _value = $(this).val();
var selectId = $(this).attr("id").slice(0, -1);
$('*[id^="' + selectId + '"]').val(_value);
});
Is there a way to add a each function to target all first row selects, instead of targeting each select by it's id?
jQuery's .on() will take a looser selector string as a parameter there. You could target all select elements in the first tr…
$( 'id-of-the-table-that-already-exists-on-page' ).on( 'change', 'tr:first-child select', function () {
// do stuff
} );
var $table = $('#foo');
function add_selects() {
$table.find('tr:first-child').html(`<select name="bar" id="bar">
<option value="1">Dynamic Option 1</option>
<option value="2">Dynamic Option 2</option>
</select>`);
}
// set listener
$table.on('change', 'tr:first-child select', function(event) {
console.log('Change! Value is: ' + $(event.target).val());
});
// modify DOM
add_selects();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="foo">
<tr>
<td>[select goes here]</td>
</tr>
<tr>
<td>
<select name="baz" id="baz">
<option value="a">Option A</option>
<option value="b">Option B</option>
</select>
</td>
</tr>
</table>
You might have to modify that to accommodate for any thead,tbody, or tfoot elements.
I am attempting to learn CodeIgniter. I want to send checkbox values from my view (index.php), via my controller (also called index.php confusingly, but that is what it is called at my company i work at, is this a good idea?), to an iFrame (which has a file called results.php) within my view. So far I get an array on view but only keys being shown - no values from checkboxes - like this:
Array ( [resultsAreaCode] => [resultsNumberType] => [resultsOrder] => [fred] => DAVE [sheep] => cow ) TEST
Here is my view with checkboxes and target iframe, note that one checkbox is populated by PHP/SQL:
<form id="numberOrderForm" action="index/localNumberResults" method="post" enctype='multipart/form-data'>
<div class="wrappers" id="multi-select1Wrapper">
<h2>Area Code</h2>
<select class="dropDownMenus" id="multi-select1" name="multi_select1[]" multiple="multiple">
<?php
//The query asking from our database
$areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
FROM `AreaCodes` ac"; //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'
$areaCodeResults = $conn->query($areaCodeSQL); // put results of SQL query into this variable
if ($areaCodeResults->num_rows > 0) { // if num_rows(from $results) is greater than 0, then do this:
// output data of each row
foreach($areaCodeResults as $areaCodeResult) //for each item in $areCodeResults do this:
{
$areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them
$areaName = $areaCodeResult['AreaName']; // get AreaName
$areaCode = $areaCodeResult['AreaCode']; //get AreaCode
?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables
}
}
?>
</select>
</div>
<div class="wrappers" id="multi-select2Wrapper">
<h2>Number Type</h2>
<select class="dropDownMenus" id="multi-select2" name="multi_select2[]" multiple="multiple">
<option class="menuoption2" name="package" value="gold">Gold</option>
<option class="menuoption2" name="package" value="silver">Silver</option>
<option class="menuoption2" name="package" value="bronze">Bronze</option>
</select>
</div>
<div class="wrappers" id="multi-select3Wrapper">
<h2>Order</h2>
<select class="dropDownMenus" id="multi-select3" name="multi_select3[]" >
<option class="menuoption3" name="order" value="sequential">Sequential</option>
<option class="menuoption3" name="order" value="random">Random</option>
</select>
</div>
<input type="submit" value="Submit">
</form>
<div id="resultsTableWrapper">
<iframe id="resultsTable" src="http://my-company.com/localNumberResults" width="100%"></iframe>
</div>
This is within my controller (this I have been told by my tutor is correct though):
class Index extends CI_Controller { // this is my controller!
public function localNumberResults()
{
$data['formdata']= array(
'resultsAreaCode' => $this->input->post("menuAreaCode"),
'resultsNumberType' => $this->input->post("package"),
'resultsOrder' => $this->input->post("order"),
'fred' => 'DAVE',
'sheep' => 'cow'
);
$data['contentlocation'] = 'system/results';
$this->load->view('system/template', $data);
}
}
Can anyone point me in the right direction where i am going wrong? :-)
guys.
I'm trying to call some AJAX Post trhu AngularJS, and I want to send all properties from my $scope variable. I have this form:
<div ng-controller="DiscountPrintsCtrl">
<div>
Choose the year:
<select ng-model="selectedYear" ng-change="searchCourses()">
<option ng-repeat="year in years" value="{{year.ID}}">{{year.Name}}</option>
</select>
</div>
<div>
Choose the course:
<select ng-model="selectedCourse" ng-change="searchStudents()">
<option ng-repeat="course in courses" value="{{course.ID}}">{{course.Nome}}</option>
</select>
</div>
<div>
Choose the student:
<select ng-model="selectedStudent" ng-change="searchStudentDetails()">
<option ng-repeat="student in students" value="{{student.ID}}">{{student.Name}}</option>
</select>
</div>
<div ng-model="studentDetails">
Details about the student:<br /><br />
<label>Name: {{studentDetails.Name}}</label><br />
<label>Number: {{studentDetails.Number}}</label><br />
<label>Print quote: {{studentDetails.PrintQuote}}</label><br />
</div>
<div>
<table>
<thead><tr>
<td></td>
<td>Title</td>
<td>Grade</td>
<td>Summary</td>
<td>Author</td>
<td>Number of pages</td>
</tr></thead>
<tbody>
<tr ng-repeat="publication in publications">
<td><input type="checkbox" ng-model="publication.Selected" /></td>
<td>{{publication.Title}}</td>
<td>{{publication.Grade}}</td>
<td>{{publication.Comments}}</td>
<td>{{publication.Author}}</td>
<td>{{publication.NumberOfPages}}</td>
</tr>
</tbody>
</table>
</div>
<button ng-click="submitForm()" value="Confirm discounts" />
And I have this JS:
<script type="text/javascript">
function DiscountPrintsCtrl($scope, $http) {
$http.get(url).success(function (years) {
$scope.years = years;
$scope.selectedYear = '';
});
$scope.searchCourses = function() {
var url = '/json/GetCoursesFromYear?' +
'selectedYear=' + $scope.selectedYear;
$http.get(url).success(function (courses) {
$scope.course = courses;
$scope.selectedCourse= '';
});
}
$scope.searchAlunosAnoSemestre = function() {
var url = '/json/GetStudentsFromCouse?' +
'selectedCourse=' + $scope.selectedCourse;
$http.get(url).success(function(students) {
$scope.students = students;
$scope.selectedStudent = '';
});
}
$scope.searchStudentDetails = function() {
var url = '';
url = '/json/GetStudentDetails?' +
'selectedStudent=' + $scope.selectedStudent;
$http.get(url).success(function(studentDetails) {
$scope.studentDetails= studentDetails;
});
url = '/json/GetPublicationsForStudent?' +
'selectedStudent=' + $scope.selectedStudent;
$http.get(url).success(function(publications) {
$scope.publications = publications;
});
}
$scope.submitForm = function () {
// How to submit the entire $scope???
}
}
Any idea? Any considerations about my JS code??
Thanks all!!!
You have typos to fix, friend:
In the .js:
$scope.course = courses;
Should be $scope.courses!
In the html:
{{course.Nome}}
Shouldn't it be:
{{course.Name}}
?
I see some Spanish (?) above there but everywhere else you say .Name so it's best to be consistent, right?
That said, it seems fine to load an object into your $scope from the external json data store as you seem do be doing in each function, loading from the json URLs. The commenters on your post didn't seem to recognize this? I think they believe you're trying to permanently store this data in $scope? Maybe I'm not seeing something that they are... but if you don't add your data model object sometime into $scope.something then {{something}} simply won't work, and neither will {{something.else}}.
Am I way off base here?