A dropdown in the laravel for filtering table data - laravel

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();
}
}
});
});

Related

#foreach data collection inside Ajax (Laravel)

I'm completely new to ajax and trying to find a workaround how to complete these scenario since I can't find any that works for me.
I'm finding a way to populate the dropdown selection using foreach using AJAX. How I'm able to achieve it? I'm completely stuck here. Here's the AJAX script.
$('#kelompokumur_id').change(function() {
var id = $(this).val();
$.ajax({
url: "{{url('fetch-anak')}}/"+id,
type: 'get',
dataType: 'json',
success: function(response) {
if(response.success){
let dataArray = response.data
$('#data_anak').empty()
let res = dataArray.map((person, index) => {
let list = `
<tr class="btn-reveal-trigger">
<td>${person.user.name}</td>
<td></td>
<td class="text-end">
<select class="form-select form-select-sm" aria-label=".form-select-sm example" name="absensi[${person.id}]">
<option value="">Pilih Absensi</option>
<option value="1">PRESENT</option>
<option value="2">PERMIT</option>
<option value="3">SICK</option>
<option value="4">ALPHA</option>
</select>
</td>
</tr>
`;
$('#data_anak').append(list);
});
}
}
});
});
And here's the script that I tried to get the collection,
return view('anak.absensi._inputabsen', compact('data_ku'));```
I tried this method, but it returns null since it's the closest I can get. Others show errors.
let list = `
<tr class="btn-reveal-trigger">
<td>${person.user.name}</td>
<td></td>
<td class="text-end">
<select class="form-select form-select-sm" aria-label=".form-select-sm example" name="absensi[${person.id}]">`
#foreach($data_ku -> item)
<option value="{{$item -> id}}">{{$item -> attendance -> status}</option>
#endforeach
`</select>
</td>
</tr>
`;
On controller:
public function create()
{
$data_ku = KelompokUmur::all();
$kabsen = kodeabsensi::all();
// dd($kabsen->toArray());
return view('anak.absensi._inputabsen', compact('data_ku', 'kabsen'));
}
when I dd($data_ku), this returns:
0 => array:6 [▼
"id" => 1
"kode_absen" => "AM"
"nama_absen" => "Anak Malas"
"keterangan" => "Anak Malas"
"created_at" => "2023-01-13T17:27:49.000000Z"
"updated_at" => "2023-01-13T17:27:49.000000Z"
]
Any help would be appreciated, thanks!
While in the *.blade.php file you can do something like this. I did it outside of the script tags but you can also perform it inside:
#php
$data_ku_item_options = '';
foreach ($data_ku as $item) {
$data_ku_item_options .= "<option value=\"" . $item->id . "\">" . $item->attendance->status . "</option>";
}
#endphp
<script>
$('#kelompokumur_id').change(function () {
var id = $(this).val();
$.ajax({
url: "{{url('fetch-anak')}}/" + id,
type: 'get',
dataType: 'json',
success: function (response) {
if (response.success) {
let dataArray = response.data
$('#data_anak').empty()
let res = dataArray.map((person, index) => {
var options = "{{ $data_ku_item_options }}";
let list = `
<tr class="btn-reveal-trigger">
<td>${person.user.name}</td>
<td></td>
<td class="text-end">
<select class="form-select form-select-sm" aria-label=".form-select-sm example" name="absensi[${person.id}]">
${options}
</select>
</td>
</tr>
`;
$('#data_anak').append(list);
});
}
}
});
});
</script>
And $data_ku = KelompokUmur::all(); change this line to:
$data_ku = KelompokUmur::with('attendance')->get();
Use this to get the collection of array in the JS
var absen = {!! json_encode($kabsen->toArray()) !!}
Then iterate it using $.each method in jQuery
$.each(absen, function(index, value) {
list += `<option value="${value.id}">${value.kode_absen}</option>`;
});
list +=

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);
}

trying to integrate ajax autocomplete in my create record in laravel

I found a ajax auto complete and I wan't it to integrate to my form but I can't make it work. Please advise thank you!
[controller]
<?php
namespace App\Http\Controllers;
use App\Purchasetransactions;
use App\AjaxAutocompleteController;
use App\Products;
use App\Categories;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class PurchasetransactionsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$purchasetransactions = Purchasetransactions::all();
return view('orders.index', compact('purchasetransactions'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('orders.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$purchasetransactions = Purchasetransactions::create($request->only('products_code','name'));
return redirect(route('orders.index'));
}
/** Auto Complete */
public function productSearch(Request $request){
$query = $request->get('term','');
$products=\DB::table('products');
if($request->type=='product_code'){
$products->where('product_code','LIKE','%'.$query.'%');
}
if($request->type=='product_name'){
$products->where('name','LIKE','%'.$query.'%');
}
$products=$products->get();
$data=array();
foreach ($products as $product) {
$data[]=array('product_code'=>$product->product_code,'name'=>$product->name);
}
if(count($data))
return $data;
else
return ['product_code'=>'','name'=>''];
}
}
[create.blade]
<div class="container">
{!! Form::open(array('route'=>'orders.store')) !!}
<table class="table table-bordered">
<tr>
<th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
<th>S. No</th>
<th>Product Code</th>
<th>product name</th>
</tr>
<tr>
<td><input type='checkbox' class='chkbox'/></td>
<td><span id='sn'>1.</span></td>
<td><input class="form-control autocomplete_txt" type='text' data-type="product_code" id='product_code_1' name='product_code[]'/></td>
<td><input class="form-control autocomplete_txt" type='text' data-type="product_name" id='product_name_1' name='product_name[]'/> </td>
</tr>
</table>
<button type="button" class='btn btn-danger delete'>- Delete</button>
<button type="button" class='btn btn-success addbtn'>+ Add More</button>
{!! Form::close() !!}
</div>
<script type="text/javascript">
$(".delete").on('click', function() {
$('.chkbox:checkbox:checked').parents("tr").remove();
$('.check_all').prop("checked", false);
updateSerialNo();
});
var i=$('table tr').length;
$(".addbtn").on('click',function(){
count=$('table tr').length;
var data="<tr><td><input type='checkbox' class='chkbox'/></td>";
data+="<td><span id='sn"+i+"'>"+count+".</span></td>";
data+="<td><input class='form-control autocomplete_txt' type='text' data-type='product_code' id='product_code_"+i+"' name='product_code[]'/></td>";
data+="<td><input class='form-control autocomplete_txt' type='text' data-type='product_name' id='product_name_"+i+"' name='product_name[]'/></td></tr>";
$('table').append(data);
i++;
});
function select_all() {
$('input[class=chkbox]:checkbox').each(function(){
if($('input[class=check_all]:checkbox:checked').length == 0){
$(this).prop("checked", false);
} else {
$(this).prop("checked", true);
}
});
}
function updateSerialNo(){
obj=$('table tr').find('span');
$.each( obj, function( key, value ) {
id=value.id;
$('#'+id).html(key+1);
});
}
//autocomplete script
$(document).on('focus','.autocomplete_txt',function(){
type = $(this).data('type');
if(type =='product_code' )autoType='product_code';
if(type =='product_name' )autoType='name';
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
$.ajax({
url: "{{ route('productsearch') }}",
dataType: "json",
data: {
term : request.term,
type : type,
},
success: function(data) {
var array = $.map(data, function (item) {
return {
label: item[autoType],
value: item[autoType],
data : item
}
});
response(array)
}
});
},
select: function( event, ui ) {
var data = ui.item.data;
id_arr = $(this).attr('id');
id = id_arr.split("_");
elementId = id[id.length-1];
$('#product_code_'+elementId).val(data.product_code);
$('#product_name_'+elementId).val(data.name);
}
});
});
</script>
[route]
Route::get('/orders/create','PurchasetransactionsController#create')->name('orders.create');
Route::get('productsearch', ['as'=>'productsearch','uses'=>'PurchasetransactionsController#productsearch']);
I've added multiple autocomplete searches to input fields in laravel, and i've always had to look it back up each time i've implemented it. This is working for me. Here is the input which i'm searching for matching abbreviations in my search
<div class="input-group">
#if(isset($_GET['variable_name']))
<input value="{{$_GET['variable_name']}}" type="search" name="variable_name" class="form-control" id="variable_name" autocomplete="off">
#else
<input type="search" name="variable_name" class="form-control" id="variable_name" placeholder="Search" autocomplete="off">
#endif
</div>
Script to control ajax return:
$(document).ready(function($) {
// Set the Options for "Bloodhound" suggestion engine
var engine = new Bloodhound({
remote: {
url: '/find?variable_name=%QUERY%',
wildcard: '%QUERY%'
},
datumTokenizer: Bloodhound.tokenizers.whitespace('variable_name'),
queryTokenizer: Bloodhound.tokenizers.whitespace
});
$('#variable_name').typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
name: 'abbreviations',
source: engine,
display: function(data) {
console.log(data);
return data.abbreviation //Input value to be set when you select a suggestion.
},
templates: {
empty: [
'<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'
],
header: [
'<div class="list-group search-results-dropdown">'
],
suggestion: function(data) {
return '<div style="font-weight:normal; margin-top:-10px ! important;" class="list-group-item">' + data.abbreviation + ' ' + data.table + '</div></div>'
}
}
});
});
Controller function
public function find(Request $request) {
$result=Abbreviation::where('abbreviation', 'LIKE', "%{$request->input('variable_name')}%")
->orWhere('name', 'LIKE', "%{$request->input('variable_name')}%")->get();
return response()->json($result);
}
My Route:
Route::get('/find', 'PagesController#find')->name('typeahead.search');
libraries:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Also need the bloodhound.js and tyepahead.jquery

Error 405: Method not allowed, EditUser route can't get info

So I've been learning Laravel and was getting into making DataTables. However, my 'editItem' route is not being able to get any information when I click 'Edit' button. It shows Error 405.
DataTable view (dt.blade.php) -
HTML part where the table is displayed
<div class="table-responsive text-center">
<table class="table table-borderless" id="table">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Name</th>
<th class="text-center">Created At</th>
<th class="text-center">Updated At</th>
<th class="text-center">Actions</th>
</tr>
</thead>
#foreach($users as $user)
<tr class="user{{$user->id}}">
<td >{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->created_at}}</td>
<td>{{$user->updated_at}}</td>
<td><button class="edit-modal btn btn-info"
value="{{$user->id}},{{$user->name}}">
<span class="glyphicon glyphicon-edit"></span> Edit
</button>
<button class="delete-modal btn btn-danger"
value="{{$user->id}},{{$user->name}}">
<span class="glyphicon glyphicon-trash"></span> Delete
</button></td>
</tr>
#endforeach
</table>
</div>
JS part in the same file
<script>
$(document).ready(function() {
$('#table').DataTable();
} );
</script>
<script>
$(document).on('click', '.edit-modal', function() {
$('#footer_action_button').text("Update");
$('#footer_action_button').addClass('glyphicon-check');
$('#footer_action_button').removeClass('glyphicon-trash');
$('.actionBtn').addClass('btn-success');
$('.actionBtn').removeClass('btn-danger');
$('.actionBtn').removeClass('delete');
$('.actionBtn').addClass('edit');
$('.modal-title').text('Edit');
$('.deleteContent').hide();
$('.form-horizontal').show();
var stuff = $(this).val().split(',');
console.log($(this).val());
fillmodaluser(stuff)
$('#myModal').modal('show');
});
$(document).on('click', '.delete-modal', function() {
$('#footer_action_button').text(" Delete");
$('#footer_action_button').removeClass('glyphicon-check');
$('#footer_action_button').addClass('glyphicon-trash');
$('.actionBtn').removeClass('btn-success');
$('.actionBtn').addClass('btn-danger');
$('.actionBtn').removeClass('edit');
$('.actionBtn').addClass('delete');
$('.modal-title').text('Delete');
$('.deleteContent').show();
$('.form-horizontal').hide();
var stuff = $(this).val().split(',');
console.log($(this).val('info'));
$('.did').text(stuff[0]);
$('.dname').html(stuff[1]);
$('#myModal').modal('show');
});
function fillmodaluser(details){
$('#fid').val(details[0]);
$('#name').val(details[1]);
}
$('.modal-footer').on('click', '.edit', function() {
$.ajax({
type: 'post',
url: '../public/editUser',
user: {
'_token': $('input[name=_token]').val(),
'id': $('#fid').val(),
'name': $('#name').val()
},
success: function(user) {
if (user.errors){
$('#myModal').modal('show');
if(user.errors.name) {
$('.name_error').removeClass('hidden');
$('.name_error').text("Name can't be empty !");
}
if(user.errors.email) {
$('.email_error').removeClass('hidden');
$('.email_error').text("Email must be a valid one !");
}
}
else {
$('.error').addClass('hidden');
$('.user' + users.id).replaceWith("<tr class='users" + users.id + "'><td>" +users.id + "</td><td>" + users.name+"</td><td>" + "</td><td>" + "</td><td><button class='edit-modal btn btn-info' user-info='" + users.id+","+users.name+"'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' user-info='" + users.id+","+users.name+"' ><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
}}
});
});
$('.modal-footer').on('click', '.delete', function() {
$.ajax({
type: 'post',
url: '../public/deleteUser',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
user: {
'_token': $('input[name=_token]').val(),
'id': $('.did').text()
},
success: function(user) {
$('.user' + $('.did').text()).remove();
}
});
});
</script>
And lastly, the web.php
Route::get('/dt', 'UserController#dt');
Route::get('/editUser', function (Request $request) {
$rules = array (
'name' => 'required|alpha',
);
$validator = Validator::make(Input::all(), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag()->toArray ()
) );
else {
$user->id = User::find ( $request->id );
$user->name = ($request->name);
$user->save ();
return response ()->json ( $user );
}
});
Route::get ('/deleteUser', function (Request $request) {
User::find ( $request->id )->delete ();
return response ()->json ();
});
The JSON error that shows to me is "{"errors":{"name":["The name field is required."]}}"
My question is that, the info can be split fine in the JQuery here when I press the Edit button; it is able to show the info of the row I've selected. I don't understand why the same values aren't getting sent to my editUser route?
change all get method to post , because you are using post in client side
Route::post('/dt', 'UserController#dt');
Route::post('/editUser', function (Request $request) {
$rules = array (
'name' => 'required|alpha',
);
$validator = Validator::make(Input::all(), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag()->toArray ()
) );
else {
$user->id = User::find ( $request->id );
$user->name = ($request->name);
$user->save ();
return response ()->json ( $user );
}
});
Route::post ('/deleteUser', function (Request $request) {
User::find ( $request->id )->delete ();
return response ()->json ();
});
Seems your urls should not be '../public/' (in your ajax requests) but it should match what you typed in your file web.php

model to fetch single result from db with jquery

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.

Resources