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);
}
Related
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
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();
}
}
});
});
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
I am using Ajax to replace a part of my page with a partial view containing multiple submit forms. This normally works when I use a normal Html.BeginForm and reload the entire page (the submit forms loaded work). However, when using Ajax to load the submit form, they display normally on the page but are not working.
I have looked around for information, but the information I have found mainly concerns submitting form through Ajax call, not loading submit forms.
This is the main View containing the javascript.
#model List<SrrManager.Models.User>
#{
ViewBag.Title = "Create";
}
<script>
$(function () {
$('Body').keypress(function (e) {
if (e.which == 13) {
$('#nomButton').trigger('click');
}
});
$('#nomButton').keyup(function (e) {
if (e.which == 13) {
$('#nomButton').trigger('click');
}
});/*
$('#prenomButton').keypress(function (e) {
if (e.which == 13) {
$('#nomButton').trigger('click');
}
});*/
$("#nomButton").on('click', function () {
var givenName = $("#prenomBox").val();
var nom = $("#nomBox").val();
$.ajax({
url: '#Url.Action("Create", "ManageUser")', //+ "?firstname=" + givenName + "&lastname=" + lastname,
type: 'GET',
data: { prenom: givenName, nomFamille: nom },
success: function (result) {
$('#liste-user').replaceWith(result);
}
});
});
});
</script>
<body>
<h2>Add an user</h2>
<p>
<label class="label-form">Prenom :</label>#Html.TextBox("prenomBox")
<br />
<label class="label-form">Nom :</label> #Html.TextBox("nomBox")
<br />
<input type="button" value="Filter" id="nomButton" />
</p>
#Html.Partial("_Create", Model)
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</body>
The _Create PartialView is as follow :
#model List<SrrManager.Models.User>
<div id="liste-user">
<table>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Email
</th>
<th>
Admin
</th>
<th></th>
</tr>
#foreach(var item in Model)
{
<tr>
<td>
#item.Name
</td>
<td>
#item.LastName
</td>
<td>
#item.email
</td>
#Html.Partial("__create", item)
</tr>
}
</table>
</div>
The last PartialView is used to create the submit form. The model is not a List but only User, and it is included once in each loop :
#model SrrManager.Models.User
#using(Html.BeginForm()){
<fieldset>
<legend>User</legend>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(x => x.Name)
#Html.HiddenFor(x => x.LastName)
#Html.HiddenFor(x => x.email)
#Html.HiddenFor(x => x.account)
<td>
#Html.EditorFor(x => x.IsAdmin)
</td>
<td>
<input type="submit" value="save" />
</td>
</fieldset>
}
The list of user and the submit form is displayed normally using Ajax call or synchronous JQuery call when clicking on the Filter button, and the controller method is called as intended. However, the buttons work when loaded with synchronous JQuery calls, but not when loaded through Ajax.
The controller method is :
public ActionResult Create(string prenom ="", string nomFamille ="")
{
List<User> listeUser = new List<User>();
if (prenom.Equals("") && nomFamille.Equals(""))
{
}
else if (prenom.Equals(""))
{
string search = "*" + nomFamille + "*";
listeUser = SearchDirectory(search, 1);
}
else if (nomFamille.Equals(""))
{
string search = "*" + prenom + "*";
listeUser = SearchDirectory(search, 2);
}
else
{
string search = "*" + prenom + "*" + nomFamille + "*";
listeUser = SearchDirectory(search, 3);
}
if (Request.IsAjaxRequest())
{
return PartialView("_Create", listeUser);
}
return View(listeUser);
}
I am a beginner using Ajax, and I am at lost as to why it does not work. If any one has any lead, it would be very appreciated.
Try adding a jQuery handler for form submits.
$('form').submit(function () {
var givenName = $("#prenomBox").val();
var nom = $("#nomBox").val();
$.ajax({
url: '#Url.Action("Create", "ManageUser")', //+ "?firstname=" + givenName + "&lastname=" + lastname,
type: 'GET',
data: { prenom: givenName, nomFamille: nom },
success: function (result) {
$('#liste-user').html(result);
}
});
});
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.