model to fetch single result from db with jquery - codeigniter

I have a controller function which is called by jquery:
function get_sku_prices(){
$this->load->model('Sales_model');
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$this->Sales_model->get_sku_price($q);
}
}
The model, get_sku_price is:
function get_sku_price($q){
$this->db->select('price');
$this->db->where('sku', $q);
$query = $this->db->get('products');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['price'])); //build an array
}
$this->output->set_content_type('application/json')->set_output(json_encode($row_set));
}
}
what I want, is to return the result of the above query(which is essentially select price from products where sku=36113) to the input variable 'price' on my view form.
My view syntax is:
<html>
<head>
<title>
Capture blank Order
</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url() ?>css/sales.css" />
<script type="text/javascript">
function callAutocomplete(element)
{
$(element).autocomplete(
{
source: "sales/get_sku_codes",
messages:
{
noResults: '',
results: function() {}
},
select: function( event, ui )
{
var selectedObj = ui.item;
$.post('sales/get_sku_prices', {data:selectedObj.value},function(result) {
$(ui).parent('tr').find('input[id^="pricepercube"]').val(result);
});
}
});
}
$(function()
{
var counter = 1;
jQuery("table.authors-list").on('change','input[name^="qty"]',function(event)
{
event.preventDefault();
counter++;
var newRow = jQuery('<tr>'+
' <td><a class="deleteRow"> x </a></td>' +
' <td><input type="text" id="product' + counter + '" name="product' + counter + '" /></td>' +
' <td><input type="text" id="qty' + counter + '" name="qty' + counter + '" /></td>'+
' <td><input type="text" id="price' + counter + '" name="price' + counter + '" /></td>'+
' <td><input type="text" id="discount' + counter + '" name="discount' + counter + '" /></td>'+
' <td valign=top><input type="checkbox" id="treated' + counter + '" name="treated' + counter + '" /></td>'+
' </tr>');
jQuery('table.authors-list').append(newRow);
callAutocomplete("#product"+ counter);
});
$("#product").autocomplete(
{
source: "sales/get_sku_codes",
messages:
{
noResults: '',
results: function() {}
},
select: function( event, ui )
{
var selectedObj = ui.item;
$.post('<?=site_url("sales/get_sku_prices")?>', {data:selectedObj.value},function(result)
{
$("#price").val(result);
});
}
});
});
</script>
</head>
<body>
<table class="authors-list" border=0>
<tr><td></td><td>Product</td><td>Qty</td><td>Price/Cube</td><td>Discount</td><td>treated</td></tr>
<tr>
<td><a class="deleteRow"> x </a></td>
<td><input type="text" id="product" name="product" /></td>
<td><input type="text" id="qty" name="qty" /></td>
<td><input type="text" id="price" name="price" /></td>
<td><input type="text" id="discount" name="discount" /></td>
<td valign="top" ><input type="checkbox" id="treated" name="treated" /></td>
</tr>
</table>
</body>
</html>
Firefox returns a 200 OK message. you can see the post information contains the contents of the product input, but the returned HTML is blank?
UPDATE
mysql
post
blank html
is my model query correct? is the post being correctly passed tot he model? how can I verify this?
Thanks again.

You are passing data inside $.post and getting it as term.
Change
if (isset($_GET['term'])){
to
if (isset($_POST['data'])){

You should be outputing your data from the controller, not the model.
Controller:
function get_sku_prices(){
$this->load->model('Sales_model');
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$data = $this->Sales_model->get_sku_price($q);
$this->output->set_content_type('application/json')->set_output(json_encode(data));
}
}
Model:
function get_sku_price($q){
$this->db->select('price');
$this->db->where('sku', $q);
$query = $this->db->get('products');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['price'])); //build an array
}
return $row_set;
}
}
Further to the above, you are passing your data via AJAX as POST data, yet in your controller you are trying to receive data from the GET array.

Related

message: "Undefined index: SKU"

When i do dd($data); all data will shown but when i remove dd and simply submit my form then problem always come undefined index sku.
This is my controller for product attribute
public function addProductAttributes(Request $request){
if($request->isMethod('post')){
$data=$request->all();
foreach($data['sku'] as $key => $value){
if($value != null){
$attr = new ProductsAttribute();
$attr->product_id = $data['product_id'][$key];
$attr->sku = $data['sku'][$key];
$attr->stock=$data['stock'][$key];
$attr->price= $data['price'][$key];
$attr->size= $data['size'][$key];
$attr->status= $data['status'][$key];
$attr->save();
}
}
}
if($request->expectsJson()){
return response()->json([
'message'=>'Product has been Update Successfully',
]);
};
}
This is my Product Attribute Template. This is Dynamically Add / Remove input fields in Vue js so i can i add multiple data array
<form role="form" method="POST" #submit.prevent="addProductAttribute">
<table >
<tbody>
<tr v-for="(attr,index) in attribute" :key="index">
<td><input type="text" v-model="product_id" class="form-control"></td>
<td><input type="text" v-model="attr.sku" placeholder="SKU" class="form-control"></td>
<td><input type="text" v-model="attr.size" placeholder="Size" class="form-control"></td>
<td><input type="text" v-model="attr.stock" placeholder="Stock" class="form-control"></td>
<td><input type="text" v-model="attr.price" placeholder="Price" class="form-control"></td>
<td><input type="text" v-model="attr.status" placeholder="Status" class="form-control"></td>
<td><a #click="addAttribute()" v-show="index == attribute.length-1" title="Add More Product Attribute"><i class="fas fa-plus" style="color: #00b44e"></i></a> <a title="Remove" #click="removeAttribute(index)" v-show="index || ( !index && attribute.length > 1)"><i class="fas fa-minus" style="color: red"></i></a></td>
</tr>
</tbody>
<tfoot>
<tr><button type="submit" class=" btn-outline-primary btn-lg">Add</button></tr>
</tfoot>
</table>
</form>
and my Script file is
<script>
export default {
mounted() {
let app = this;
let id = app.$route.params.id;
app.product_id = id;
this.readProductAttribute();
},
data(){
return{
product_id:'',
product_name:'',
attributes:[],
product:'',
attribute:[
{
product_id:'',
sku:'',
price:'',
stock:'',
size:'',
status:'',
}
]
}
},
methods: {
removeAttribute(index){
this.attribute.splice(index, 1);
},
addAttribute(){
this.attribute.push({ size: '',sku:'',price:'',stock:'',status:'' });
},
addProductAttribute: function(e){
axios.post(`/admin/add-product-attribute`,{
myArray: this.attribute
})
.then(function(response){
console.log(response);
})
}
}
}
Your data lies within the key 'myArray' so changing the loop to the following should help on your error.
foreach($data['myArray'] as $key => $value){
The access logic for each attr is also flawed. You should only access it on their key, secondly it seems like product_id is not always there in your data, so you can use nullcoalescent to return empty string if key is not there.
$attr->product_id = $data['product_id'] ?? '';
$attr->sku = $data['sku'] ?? '';
$attr->stock=$data['stock'] ?? '';
$attr->price= $data['price'] ?? '';
$attr->size= $data['size'] ?? '';
$attr->status= $data['status'] ?? '';

How to get the last record from database using ajax

I am using ajax to get some students data from database. And I have separate markup inside ajax for that data to display in the table. Now what I wanna do is to get the last inserted record or the latest record on the top but I have no I idea how to do that. I use sortByDesc() function but that does not work in this case. Below is my code. Help :)
Ajax Call
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/attendance/ajax/' + classID,
type: "GET",
dataType: "json",
success: function (data) {
var table = $('table[id="studentsData"]');
table.DataTable().destroy();
var markup = '';
markup = '<thead><tr><th style="width: 2%" class="align-middle text-center"><input type="checkbox" id="options"></th><th style="width: 15%" class="text-center">Student ID</th> <th style="width: 15%" class="text-center">Student Name</th> <th style="width: 15%" class="text-center">Attendance</th> <th style="width: 15%" class="text-center">Date</th> <th style="width: 15%;" class="align-middle text-center">Actions</th> </tr></thead><tbody>';
$.each(data, function (key, value) {
markup += '<tr> <td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="' + value.id + '"></td> <td class="text-center align-middle"><input type="hidden" value="' + value.student_id + '" name="student_id[]">' + value.student_id + '</td> <td class="text-center align-middle"><input type="hidden" value="' + value.first_name + '" name="first_name[]"><input type="hidden" value="' + value.last_name + '" name="last_name[]">' + value.first_name + ' ' + value.last_name + '<td class="text-center align-middle"><input type="hidden" value="' + value.attendance + '" name="attendance[]">' + value.attendance + '</td>' + '<td class="text-center align-middle"><input type="hidden" value="' + value.date + '" name="date[]">' + value.date + '</td>' + '<td style=" width=12%" class="text-center"> <a data-toggle="modal" data-target="#editAttendanceModal' + value.id + '"><button title="Edit" class="btn btn-primary"><span class="fas fa-pencil-alt"></span></button></a> <a data-toggle="modal" data-target="#deleteAttendanceModal' + value.id + '"><button title="Delete" class="btn btn-danger"><span class="fas fa-trash-alt"></span></button></a> </td>' + '</td> </tr>';
});
markup += '</tbody>';
var table = $('table[id="studentsData"]');
table.html(markup);
table.DataTable();
}
});
}
});
**Controller**
public function myAttendanceAjax($id) {
$students_register = StudentsAttendance::where('class_id', $id)->get();
return json_encode($students_register);
}
You can use orderBy('id', 'desc')->get(); for geting latest record.
There is a method latest() defined in Illuminate\Database\Query\Builder Class.
public function latest($column = 'created_at')
{
return $this->orderBy($column, 'desc');
}
So, It will just orderBy with the column you provide in descending order with the default column will be created_at.
For more information about sorting have a look at https://laravel.com/docs/5.8/queries#ordering-grouping-limit-and-offset

Getting the right values from IDs in Laravel

I have a problem in getting the actual values from ids. I can't understand the issue because while storing these values I am getting them using Ajax in a dropdown where it stores its ids from the dropdown. But when I am trying to get these values back, then it shows me those ids and not the actual values. I can't understand how I can get the actual values from these ids. I also plucked them in my index method in the controller, but that's not working because it's Ajax. Below is my code, please let me know if you want to know anything more about this.
Controller actions for creating the form.
public function create()
{
$classes = StudentsClass::pluck('class_name', 'id')->all();
$rep_cat = ReportCtegories::pluck('name', 'id')->all();
return view('admin.reports.create', compact('classes', 'rep_cat'));
}
public function getStudentId($id)
{
$students = DB::table("students")->where("students_class_id", $id)->pluck("student_id", "id");
return json_encode($students);
}
public function getStudentName($id)
{
$students = DB::table("students")->select("id", DB::raw("CONCAT(first_name, ' ', last_name) as name"))
->where("students_class_id", $id)->pluck("name", "id");
return json_encode($students);
}
Ajax for getting values.
<script>
$(document).ready(function () {
//FOR LOADING STUDENTS
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('select[name="class_id"]').on('change', function () {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/reports/ajax/' + classID,
type: "GET",
dataType: "json",
success: function (data) {
var markup = '';
markup = '<thead><tr class="filters"><th style="width: 2%" class="align-middle text-center"><input type="checkbox" id="options"></th><th style="width: 15%" class="text-center">Student ID<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Student Name<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Report Category<input type="text" class="form-control" disabled></th> <th style="width: 15%;" class="align-middle text-center">Actions</th> <tr></thead><tbody>';
$.each(data, function (key, value) {
markup += '<tr> <td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="' + value.id + '"></td> <td><input type="hidden" value="' + value.student_id + '" name="student_id[]">' + value.student_id + '</td> <td><input type="hidden" value="' + value.student_name + '" name="student_name[]">' + value.student_name + '<td><input type="hidden" value="' + value.report_categories_id + '" name="report_categories_id[]">' + value.report_categories_id + '</td>' + '<td style=" width=12%" class="text-center"> <a data-toggle="modal" data-target="#editAttendanceModal' + value.id + '"""><button title="Edit" class="btn btn-outline-primary"><span class="fas fa-pencil-alt"></span></button></a> </td>' + '</td> <tr>';
});
markup += '</tbody>';
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
</script>
First of all i recommend you use,
return response()->json($students)
Second pluck only return an array of ids(in your case)
I think you can try with this.
public function getStudentId($id)
{
$students = DB::table("students")->where("students_class_id", $id)->get();
return response()->json($students);
}

A dropdown in the laravel for filtering table data

I want to know something in Laravel. I want a dropdown for classes so when the user selects any class and press the submit button then the users related to that specific class will be displayed below in the table... Is it possible?
Below is the code I did for getting the data but I want this data to refer to my table in the HTML because there is something more I want and I can't add those things to the ajax table
//My ajax
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if(classID) {
$.ajax({
url: '/myform/ajax/'+classID,
type: "GET",
dataType: "json",
success:function(data) {
var markup = '';
$.each(data, function(key, value) {
markup += '<tr> <td>' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name+ ' ' + value.last_name + '</td> <tr>';
});
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
//Controller
public function index(Request $request){
$classes = StudentsClass::pluck('class_name', 'id')->all();
return view('admin.students.attendance.index', compact( 'classes'));
}
public function mytableAjax($id) {
$students = Student::where('students_class_id', $id)->get();
return json_encode($students);
}
//My view
<select name="students_class_id" class="form-control" style="width:350px">
<option value="">--- Select State ---</option>
#foreach ($classes as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
<table id="studentsData" class="table table-striped table-bordered table-list-search">
<thead>
<tr>
<th>#</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<select class="form-control" id="gender">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>
</td>
</tr>
</tbody>
</table>
<a class="fas fa-folder-open btn btn-success float-right mb-4 mr-2"> Save</a>
</div>
Check the following code that will add the attendance column for every row :
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/myform/ajax/' + classID,
type: "GET",
dataType: "json",
success: function(data) {
var attendance = `<div class="form-group">
<select class="form-control" id="gender" name="attendance[]">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>`;
var markup = '';
$.each(data, function(key, value) {
markup += '<tr> <td><input type="hidden" value="'+value.id+'" name="id[]">' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name + ' ' + value.last_name + '</td> <td> ' + attendance + '</td> <tr>';
});
$('#studentsData tbody').html(markup);
var thead_markup += '<tr> <th>A</th> <th>B</th> <th>C</th> <td>D</th> <tr>';
$('#studentsData thead').html(thead_markup);
}
});
}
});
});
It depends upon your code, if you are using ajax datatables api then here is a similar example:
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
} );
Reference: datatables.net multi filter select
If you are not using datatables api and do not want ajax then use below code and change according to your need:
$("#selectDropdown").on("change", function () {
var value = $(this).val();
$("table tr").each(function (index) {
if (index != 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) != 0) {
$(this).hide();
}
else {
$(this).show();
}
}
});
});

AngularJS + post the entire $scope for Controller in ASP.NET MVC

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?

Resources