Anyone can tell me whats wrong in here when im putting a array of number like :1,2 its starting to freeze the screen i hope someone can help me thanks - laravel

Hello guys im trying to learn vue and im trying to use datatable from https://datatables.net/ and having a problem with my action button that im not able to get the id when the #viewModal is been triggered i hope someone can help me to get the id of each buttons thanks and here is my code TIA:
EmployeeDataTable Component :
<template>
<div class="card">
<div class="card-header">
<div class="card-title">Employee List</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table
id="employee-table"
class="table-sm table-bordered table-hover text-center display"
width="100%"
>
<thead>
<tr>
<th class="pt-3 pb-3">#</th>
<th>Name</th>
<th>Address</th>
<th>Contact #</th>
<th>Department</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</template>
<script>
//For Datatable to work
import "datatables.net";
import EmployeeEdit from "./EmployeeEdit.vue";
export default {
name: "EmployeeList",
data() {
return {
employees: [],
};
},
mounted() {
this.getEmployeeLists();
},
components: {
"employee-edit": EmployeeEdit,
},
methods: {
getEmployeeLists() {
// INITIALIZE DATATABLE
$("#employee-table")
.DataTable({
//LOADING
// processing: true,
//AJAX
serverSide: true,
//DIRECTION
order: [[1, "desc"]],
//AJAX
ajax: {
url: "/api/getEmployeeLists",
dataList: "json",
type: "POST",
data: { _token: "{{csrf_token()}}" },
},
//TABLE COLUMNS SHOULD BE THE SAME IN CONTROLLER
columns: [
{ data: "#" },
{ data: "name" },
{ data: "address" },
{ data: "contact" },
{ data: "department" },
{ data: "status" },
{
data: "actions",
//allowing modification
createdCell(cell, cellData, rowData) {
let EmployeeListDataTableActions = Vue.extend(
require("./EmployeeListDataTableAction.vue").default
);
let instance = new EmployeeListDataTableActions().$mount();
$(cell).empty().append(instance.$el);
},
},
],
//View Count in Table
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"],
],
})
.columns();
},
beforeDestroy: function () {
$(this.$el).DataTable().destroy();
},
},
};
</script>
EmployeeDataTableAction Component :
<template>
<button class="btn btn-primary btn-sm" #click="viewModal" title="View Employee Details">
<i class="fa fa-eye"></i>
</button>
</template>
<script>
export default{
name: 'EmployeeListDataTableAction',
data: function() {
return {
}
},
mounted() {
},
methods: {
viewModal() {
var id = $(this.$el).closest('tr').find('input').val();
return false;
axios
.post(`/api/getEmployeeDetails/${id}`, {
id: id,
})
.then((response) => {
$("#edit-employee-modal").modal("show");
$(".myModalLabel").text(
response.data.name +
" - " +
response.data.department_name
);
state.commit("getEmployeeDetailsArray", response.data);
state.commit("getTransactionId", response.data.id);
})
.catch((response) => {
this.$toast.top("Something went wrong!");
});
},
},
}
</script>
Employee Controller for the DataTable :
public function employeeList(Request $request){
$all = Employee::getEmployeeTotal();
//total count of data
$total_data = $all;
//total filter
$total_filtered = $total_data;
//set_time_limit(seconds)
$limit = $request->input('length');
//start
$start = $request->input('start');
//order
// $order = $columns[$request->input('order.0.column')];
//direction
$dir = $request->input('order.0.dir');
$search_value = $request->input('search.value');
if (!empty($search_value)) {
$posts = Employee::getEmployeeNameSearch($search_value,$start, $limit, $dir);
$total_data = count($posts);
$total_filtered = $total_data;
}else{
if(empty($request->input('search.value')))
{
//if no search
$posts = Employee::getEmployeeList($start, $limit, $dir);
}
}
$data = array();
if(!empty($posts))
{
$counter = $start + 1;
foreach ($posts as $post)
{
$department = GlobalModel::getSingleDataTable('departments',$post->department_id);
$status = StatusController::checkStatus($post->status);
$nested_data['#'] = '<span style="font-size: 12px ; text-align: center;">'.$counter++.'</span>';
$nested_data['name'] = '<p style="text-align: center;">'.$post->name.'</p>';
$nested_data['address'] = '<p style="text-align: center;">'.$post->address.'</p>';
$nested_data['contact'] = '<p style="text-align: center;">'.$post->contact.'</p>';
$nested_data['department'] = '<p style="text-align: center;">'.$department->name.'</p>';
$nested_data['status'] = '<p style="text-align: center;">'.$status.'</p>';
$nested_data['actions'] = '';
$data[] = $nested_data;
}
}
$json_data=array(
"draw" => intval($request->input('draw')),
"recordsTotal" => intval($total_data),
"recordsFiltered" => intval($total_filtered),
"data" => $data
);
return response()->json($json_data);
}

In the second line of your viewModal() function, you are placing a return false; statement. "The return statement ends function execution and specifies a value to be returned to the function caller." From Mozilla docs. That's why the API call is never executing.

Related

Edit default pagination in vuejs?

I handle vuejs + laravel
I Controller :
public function listData (Request $request)
{
$currentPage = !empty($request->currentPage) ? $request->currentPage : 1;
$pageSize = !empty($request->pageSize) ? $request->pageSize : 30;
$skip = ($currentPage - 1) * $pageSize;
$totalProduct = Product::select(['id', 'name'])->get();
$listProduct = Product::select(['id', 'name'])
->skip($skip)
->take($pageSize)
->get();
return response()->json([
'listProduct' => $listProduct,
'total' => $totalProduct,
]);
}
In vuejs
data() {
return {
pageLength: 30,
columns: [
{
label: "Id",
field: "id",
},
{
label: "Name",
field: "name",
},
],
total: "",
rows: [],
currentPage: 1,
};
},
created() {
axios
.get("/api/list")
.then((res) => {
this.rows = res.data. listProduct;
this.total = res.data.total;
})
.catch((error) => {
console.log(error);
});
},
methods: {
changePagination() {
axios
.get("/api/list", {
params: {
currentPage: this.currentPage,
pageSize: this.pageLength,
},
})
.then((res) => {
this.rows = res.data. listProduct;
this.total = res.data.total;
})
.catch((error) => {
console.log(error);
});
},
},
Template :
<vue-good-table
:columns="columns"
:rows="rows"
:rtl="direction"
:search-options="{
enabled: true,
externalQuery: searchTerm,
}"
:select-options="{
enabled: false,
selectOnCheckboxOnly: true,
selectionInfoClass: 'custom-class',
selectionText: 'rows selected',
clearSelectionText: 'clear',
disableSelectInfo: true,
selectAllByGroup: true,
}"
:pagination-options="{
enabled: true,
perPage: pageLength,
}"
>
<template slot="pagination-bottom">
<div class="d-flex justify-content-between flex-wrap">
<div class="d-flex align-items-center mb-0 mt-1">
<span class="text-nowrap"> Showing 1 to </span>
<b-form-select
v-model="pageLength"
:options="['30', '50', '100']"
class="mx-1"
#input="changePagination"
/>
<span class="text-nowrap"> of {{ total }} entries </span>
</div>
<div>
<b-pagination
:value="1"
:total-rows="total"
:per-page="pageLength"
first-number
last-number
align="right"
prev-class="prev-item"
next-class="next-item"
class="mt-1 mb-0"
v-model="currentPage"
#input="changePagination"
>
<template #prev-text>
<feather-icon icon="ChevronLeftIcon" size="18" />
</template>
<template #next-text>
<feather-icon icon="ChevronRightIcon" size="18" />
</template>
</b-pagination>
</div>
</div>
</template>
I am dealing with a product list that has 500,000 products. I don't want to take it out once. I want it to pull out 30 products each time, when I click on the partition, it will call to the api to call the next 30 products.. But my problem is the default pageLength is 30 products, When I choose show showing 50 products , it still shows 30 products on the page list (But I console.log (res.data.listProduct)) it shows 50 products, how do I change the default value pageLength.
Is there any way to fix this, Or am I doing something wrong. Please advise. Thanks.
Add this into computed =>
paginationOptionsComputed(){
return { enabled: true, perPage: Number(this.pageLength), }
}
And change :pagination-options="paginationOptionsComputed"
Note: actual problem is that vue-good-table expects perPage as number. If you look at the initializePagination method in here you can see this:
if (typeof perPage === 'number') {
this.perPage = perPage;
}

daterange with timerange using codeigniter 3 and ajax

I have a daterange picker and it is fully working. However, I have a new target which is daterange with timepicker. But the thing is I don't know how to implement it like what I did on my daterange without timepicker. Is there any way where I can implement it? I have provided my codes below of my fully working daterange picker. I have provided also my screenshot of my current daterange and my target daterange with timepicker. Thank you in advance.
HTML:
<div class="img-fluid">
<div class="input-group">
From:
<input type="date" class="mr-4" id="from" name="from">
To:
<input type="date" id="to" name="to" style="margin-right:50px;">
</div>
</div>
<div class="tab-pane fade show active" id="custom-tabs-two-1" role="tabpanel" aria-labelledby="custom-tabs-two-1-tab">
<table id="testing" class="table-striped table table-head-fixed" style="min-width:1000px; width:100%;">
<thead class="" style="background-color: #404040; color: white;">
<tr>
<th scope="col"><i class="fas fa-list-ol mr-2"></i>Transaction ID</th>
<th scope="col"><i class="fas fa-list-ol mr-2"></i>Reference No.</th>
<th scope="col"><i class="far fa-calendar-alt mr-2"></i>Date Requested</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Script & Ajax:
var save_method; //for save method string
var table;
var base_url = '<?php echo base_url();?>';
$(document).ready(function() {
//datatables
var table = $('#testing').DataTable({
dom: 'lBfrtip',
buttons: [
'print', 'csv', 'copy', 'excel', 'pdfHtml5'
],
"processing": false, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('controller/ajax_list')?>",
"type": "POST",
"data": function ( data ) {
data.from = $('#from').val();
data.to = $('#to').val();
},
},
//Set column definition initialization properties.
"columnDefs": [
{
"targets": [ 0 ], //first column
"orderable": false, //set not orderable
},
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
setInterval( function () {
testing.ajax.reload(null,false);
}, 1000);
Controller:
public function ajax_list()
{
$list = $this->repo->admin();
$data = array();
$no = $_POST['start'];
foreach ($list as $person) {
$no++;
$row = array();
$row[] = $person->transID;
$row[] = $person->refNumber;
$row[] = $person->dateRequested;
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->repo->showing_pending(),
"recordsFiltered" => $this->repo->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
}
Model:
var $table = 'ca';
var $column_order = array(null,'transID','dateRequested','refNumber');
var $order = array('transID' => 'desc');
var $column_search = array('transID','dateRequested','refNumber');
//set column field database for datatable orderable //set column field database for datatable searchable just firstname , lastname , address are searchable var $order = array('id' => 'desc'); // default order
private function _get_datatables_query()
{
if($this->input->post('from')){
$this->db->where('dateCre >=', $this->input->post('from'));
$this->db->where('dateCre <=', $this->input->post('to'));
}
$this->db->from('ca');
$i = 0;
foreach ($this->column_search as $item)
{
if($_POST['search']['value'])
{
if($i===0) // first loop
{
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i)
$this->db->group_end();
}
$i++;
}
if(isset($_POST['order']))
{
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function admin()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
public function showing_pending()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
}
What is your exact error? I think that you need to sanitize your post values before the query.
Change This:
$this->db->where('dateCre >=', $this->input->post('from'));
To this (please select the correct format in your case)
$from_date = DateTime::createFromFormat('d/m/Y h:m:s', $this->input->post('from'));
$this->db->where('dateCre >=', $from_date->format('Y-m-d h:m:s'));
Do it also with the "post('to')" value.

How to pass data from controller to view using AJAX

I want to show a data controller to view using ajax and I have already shown a data controller to view on the chart bar without ajax I need to get data on the chart bar using ajax but I don't have an idea how to show data on chart bar using ajax.
I don't have that good experience in JSON/AJAX/Laravel, I'm a beginner.
Controller
public function index()
{
$manager_hourlog = Hourlog::with('project', "user")->get()-
>groupBy('project.name');
$projects = [];
$totals = [];
foreach ($manager_hourlog as $key => $val) {
$projects[] = $key;
}
foreach ($manager_hourlog as $key2 => $val) {
$minutes = $val->sum('hour_work');
$totals[] = round($minutes / 60, 1);
}
$users = User::where("status", 1)->get();
$data = [
// manager report
'manager_projects' => $projects,
'totals' => $totals,
"manager_hourlog" => $manager_hourlog,
"auth" => $auth,
];
return response()->json(['data' => $data]);
return view('cms.dashboard', $data);
}
Script
<script>
// Employee report script
var colors = ["#1abc9c", "#2ecc71", "#3498db",
"#9b59b6", "#34495e", "#16a085", "#27ae60"];
#if ($auth->user_type != 1)
// manager report script
var managerchartbar = {
labels: {!! json_encode($manager_projects) !!},
datasets: [
#foreach($users as $user)
{
label: {!! json_encode($user->name) !!},
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
// data: [300,200,500,700]
data: [
#foreach($manager_hourlog as $hourlog)
{{$hourlog->where("user_id", $user->id)->sum("hour_work") / 60}},
#endforeach
]
},
#endforeach
]
};
var ctx = document.getElementById('manager').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: managerchartbar,
options: {
title: {
display: true,
text: 'Employees Report chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
#endif
ajax
$.ajax({
type: 'GET',
url: '{{url("/dashboard")}}',
data: {
data: data
},
success: function(data){
console.log(data.data);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
</script>
Html VIew
<div class="col-md-12">
<div class="card-box">
<div class="container-fluid">
<canvas id="manager" height="100">
</canvas>
</div>
</br>
</div>
</div>
Route
Route::get('/dashboard',
'DashboardController#index')->name('dashboard');

Asp.Net Mvc Html.BeginFormSubmit ajax sends twice request (one's type xhr the other's document)

I am working on a survey application with Asp.Net MVC. I have a page named Index.cshtml which has a question table and a 'Add New' button.Once button clicked, a popup is opened with jQuery. I am calling a view from controller to fill jQuery dialog named as AddOrEdit.cshtml (child page). I am adding new question and options. Question is a textfield and its options are added in editable table. Once clicked submt button Submit form event (save or update) is fired. But ajax sends twice request. One of these requests send empty object, the other sends full object. Where am I making a mistake?
According to my research, what causes this problem is that the unobtrusive validator is placed on 2 different pages. But this is not the case for me.
When I debug with chrome in f12, the initiator of one of the 2 requests 'jquery' the initiator of the other 'other' The type of one of these 2 post requests appears as 'XHR' and the type of the other is 'document'.
Index.cshtml
#{
ViewBag.Title = "Soru Listesi";
}
<h2>Soru Oluşturma</h2>
<a class="btn btn-success" style="margin-bottom: 10px"
onclick="PopupForm('#Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Yeni Soru Oluştur</a><table id="questionTable" class="table table-striped table-bordered accent-blue" style="width: 100%">
<thead>
<tr>
<th>Soru No</th>
<th>Soru Adı</th>
<th>Oluşturma Tarihi</th>
<th>Güncelleme Tarihi</th>
<th>Güncelle/Sil</th>
</tr>
</thead>
</table>
<link
href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
rel="stylesheet" />
#section Scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function() {
dataTable = $("#questionTable").DataTable({
"ajax": {
"url": "/Question/GetData",
"type": "GET",
"datatype": "json"
},
"columnDefs": [
{ targets: 2 }
],
"scrollX": true,
"scrollY": "auto",
"columns": [
{ "data": "QuestionId" },
{ "data": "QuestionName" },
{
"data": "CreatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "UpdatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "QuestionId",
"render": function(data) {
return "<a class='btn btn-primary btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit", "Question")/" +
data +
"')><i class='fa fa-pencil'></i> Güncelle</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" +
data +
")><i class='fa fa-trash'></i> Sil</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
}
],
"language": {
"emptyTable":
"Soru bulunamadı, lütfen <b>Yeni Soru Oluştur</b> butonuna tıklayarak yeni soru oluşturunuz. "
}
});
});
function getDateString(date) {
var dateObj = new Date(parseInt(date.substr(6)));
let year = dateObj.getFullYear();
let month = (1 + dateObj.getMonth()).toString().padStart(2, '0');
let day = dateObj.getDate().toString().padStart(2, '0');
return day + '/' + month + '/' + year;
};
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function(response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Soru Detay',
modal: true,
height: 'auto',
width: '700',
close: function() {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
debugger;
if (form.checkValidity() === false) {
debugger;
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err.data);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}
function ResetForm(form) {
Popup.dialog('close');
return false;
}
function Delete(id) {
if (confirm('Bu soruyu silmek istediğinizden emin misiniz?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Question")/' + id,
success: function(data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message,
{
className: "success",
globalPosition: "top center",
title: "BAŞARILI"
})
}
}
});
}
}
</script>
}
AddOrEdit.cshtml
#using MerinosSurvey.Models
#model Questions
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Question", FormMethod.Post, new { #class = "needs-validation",
novalidate = "true", onsubmit = "return SubmitForm(this)", onreset = "return ResetForm(this)", id =
"questionForm" }))
{
<div class="form-group row">
#Html.Label("QuestionId", "Soru No", new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.QuestionId, new { #readonly = "readonly", #class = "form-control" })
</div>
</div>
<div class="form-group row">
#Html.Label("QuestionName", "Soru Adı", new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.QuestionName, new { htmlAttributes = new { #class = "form-control", required = "true" } })
<div class="valid-feedback"><i class="fa fa-check">Süpersin</i></div>
<div class="invalid-feedback "><i class="fa fa-times"></i></div>
</div>
</div>
#*<div class="form-group row">
#Html.LabelFor(model => model.CreatedDate, new { #class = "form-control-label col-md-3"})
<div class="col-md-9">
#Html.EditorFor(model => model.CreatedDate, "{0:yyyy-MM-dd}", new { htmlAttributes = new { #class = "form-control", type = "date", #readonly = "readonly",required="false" } })
</div>
</div>*#
<div class="table-wrapper form-group table-responsive-md">
<div class="table-title">
<div class="form-group row">
<div class="col-md-9">Seçenekler</div>
<div class="col-md-3">
<a class="btn btn-success add-new" style="margin-bottom: 10px"><i class="fa fa-plus"></i>Seçenek Ekle</a>
</div>
</div>
</div>
<table class="table optionTable">
<thead>
<tr>
<th scope="col">Seçenek Id</th>
<th scope="col">Seçenek Adı</th>
<th scope="col">Güncelle/Sil</th>
</tr>
</thead>
<tbody>
#*#foreach (Options options in Model.Options)
{
<tr>
<td>#options.OptionId</td>
<td>#options.OptionName</td>
<td>
<a class="add btn btn-primary btn-sm" title="Add" data-toggle="tooltip">
<i class="fa fa-check">Onayla</i></a>
<a class="edit btn btn-secondary btn-sm" title="Edit" data-toggle="tooltip"><i class="fa fa-pencil">Güncelle</i></a>
<a class="delete btn-danger btn-sm" title="Delete" data-toggle="tooltip"><i class="fa fa-trash">Sil</i></a>
</td>
</tr>
}*#
</tbody>
</table>
</div>
<div class="form-group row">
<input type="submit" value="Submit" class="btn btn-primary" id="btnSubmit" />
<input type="reset" value="Reset" class="btn btn-secondary" />
</div>
}
<script>
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
//var actions = $("table.optionTable td:last-child").html();
var actions =' <a class="add btn btn-primary btn-sm" title="Add" data-toggle="tooltip"><i
class="fa fa-check">Onayla</i></a>' + '<a class="edit btn btn-secondary btn-sm" title="Edit" data toggle="tooltip"><i class="fa fa-pencil">Güncelle</i></a>' +'<a class="delete btn-danger btn-sm" title="Delete" data-toggle="tooltip"><i class="fa fa-trash">Sil</i></a>';
// Append table with add row form on add new button click
$(".add-new").click(function () {
$(this).attr("disabled", "disabled");
var index = $("table.optionTable tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="text" class="form-control" name="optionId" id="optionId"></td>' +
'<td><input type="text" class="form-control" name="optionId" id="optionName"></td>' +
'<td>' + actions + '</td>' +
'</tr>';
$("table.optionTable").append(row);
$("table.optionTable tbody tr").eq(index + 1).find(".add, .edit").toggle();
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function () {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function () {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function () {
$(this).parent("td").html($(this).val());
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").removeAttr("disabled");
}
});
// Edit row on edit button click
$(document).on("click", ".edit", function () {
$(this).parents("tr").find("td:not(:last-child)").each(function () {
$(this).html('<input type="text" class="form-control" value="' + $(this).text() + '">');
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").attr("disabled", "disabled");
});
// Delete row on delete button click
$(document).on("click", ".delete", function () {
debugger;
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
});
});
event.preventDefault(); move this line and place it immediately after function SubmitForm (form){
Like below:
function SubmitForm(form) {
debugger;
event.preventDefault();
if (form.checkValidity() === false) {
debugger;
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err.data);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}

I need the data ,according to the type I send

My view blade that displays the data of all types but I need the specific type only, where i send it by ajax: "{{ route('taxonomies.json',type) }}".How do I send the type that I want from the given type?
<div class="table">
<table id="taxonomyTable">
<thead>
<tr>
<th>SN</th>
<th>Title</th>
<th>Parent</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="quickModal" tabindex="-1" role="dialog" aria-labelledby="quickModal" aria-hidden="true">
</div>
<input type="hidden" id="type" value="{{ $type }}" />
and the js is:
<script>
$(document).ready(function () {
var type = $('#type').val();
$('#taxonomyTable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('taxonomies.json') }}",
columns: [
{
data: 'id',
render: function (data, type, row) {
return '<strong> #' + data + '</strong>';
}
},
{
data: 'title', name: 'title',
render: function (data, type, row) {
return '<strong>' + data + '</strong>';
}
},
{
data: 'parent', name: 'parent',
render: function (data, type, row) {
return '<strong>' + data.title + '</strong>';
}
},
{
data: 'type', name: 'type',
render: function (data, type, row) {
return '<strong>' + data.type+ '</strong>';
}
},
{
data: 'status',
render: function (data, type, row) {
return data === 'Active' ? '<button class="btn btn-outline-success btn-update-status" data-id="' + row.id + '">Active</button>' : '<button class="btn btn-xs btn-outline-danger btn-update-status" data-id="' + row.id + '">Inactive</button>';
}
},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
});
</script>
and my route is:
Route::get('/taxonomies/taxonomy-json/{type}', 'Admin\TaxonomyController#taxonomyJson')->name('taxonomies.json');
and my TaxonomyController has:
public function taxonomyJson()
{
$taxonomy = Taxonomy::with('parent')->toJson();
return DataTables::of($taxonomy)
->addIndexColumn()
->addColumn('action', function ($taxonomy) {
return '<div class="table-actions float-left">
<i class="ik ik-edit-2 green"></i>
<i class="ik ik-trash-2 red"></i>
</div>';
})->make();
}
The code mentioned above displays all of the types in the data but I only need the data of given type.Like my types are category, tag, videos,slider,etc and I need the data of types category only.
How can I fetch it?
Change You Input Hidden tag to which include whole route with it's parameters
<input type="hidden" id="type" value="{{ route('taxonomies.json', ['type' => $type]) }}" />
Now, In Your Ajax call pass input hidden type value directly to ajax as url.
var type_url = $('#type').val();
ajax: type_url
This way you don't have to worry about passing dynamic param. value to JS code from PHP code.
& In Your Controller Function
public function taxonomyJson($type=null)
{
$taxonomy = Taxonomy::with('parent')
if ($type) {
$taxonomy = $taxonomy->where('type', $type);
}
$taxonomy = $taxonomy->toJson();
return DataTables::of($taxonomy)
->addIndexColumn()
->addColumn('action', function ($taxonomy) {
return '<div class="table-actions float-left">
<i class="ik ik-edit-2 green"></i>
<i class="ik ik-trash-2 red"></i>
</div>';
})->make();
}
From your question as far I understood that you want filtered data, in order to get filtered data you needed to pass a filter type which you must use to filter your query. Here is an example for you
if ($request->ajax()) {
$users = User::select(
'users.id',
'users.name',
'users_details.first_name',
'users_details.last_name',
'users.email',
'users.membership_no',
'users.is_active',
'users.created_at'
)
->leftJoin('users_details', 'users.id', '=', 'users_details.users_id')
->where('user_group', '<>', 'admin')
->where(function ($query) use ($request) {
$genery = $request->get("genere");
$varsitySession = $request->get("varsity_session");
$yearOfPassing = $request->get("year_of_passing");
$department = $request->get("department");
$bloodGroup = $request->get("blood_group");
$membership = $request->get("membership");
if (isset($genery) && $genery) {
$query->where('users_details.genre', $genery);
}
if (isset($varsitySession) && $varsitySession) {
$query->where('users_details.varsity_session', $varsitySession);
}
if (isset($yearOfPassing) && $yearOfPassing) {
$query->where('users_details.year_of_passing', $yearOfPassing);
}
if (isset($department) && $department) {
$query->where('users_details.department', $department);
}
if (isset($bloodGroup) && $bloodGroup) {
$query->where('users_details.blood_group', $bloodGroup);
}
if (isset($membership) && $membership) {
$query->where('users_details.membership', $membership);
}
if (isset($request->requested) && $request->requested == 0) {
$query->where('users.membership_no', $request->requested);
}
})
->get();
return Datatables::of($users)
->editColumn('name', function ($users) {
return ($users->first_name) ? $users->first_name . ' ' . $users->last_name : $users->name;
})
->editColumn('is_active', function ($users) {
return ($users->is_active) ? 'Active' : 'De-active';
})
->editColumn('membership_no', function ($users) {
return ($users->membership_no) ? $users->membership_no : 'Not Assigned';
})
->editColumn('created_at', function ($users) {
return $users->created_at->toDayDateTimeString();
})
->make(true);
}
Here you can see that I'm generating a query with where clause which are generated from request data
$genery = $request->get("genere");
$varsitySession = $request->get("varsity_session");
$yearOfPassing = $request->get("year_of_passing");
$department = $request->get("department");
$bloodGroup = $request->get("blood_group");
$membership = $request->get("membership");
Here genere,varsity_session,year_of_passing,department,blood_group,membership are my filter data I'm sending with request.
here is my data table code
$('.dataTable').dataTable({
destroy: true,
paging: true,
searching: true,
sort: true,
processing: true,
serverSide: true,
"ajax": {
url: '{{ url('users/datatable')}}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
'data': function (d) {
d.genere = $("#genere").val();
d.varsity_session = $("select[name = varsity_session]").val();
d.year_of_passing = $("select[name = year_of_passing]").val();
d.department = $("select[name = department]").val();
d.blood_group = $("input[name = blood_group]").val();
d.membership = $("select[name = membership]").val();
d.paymentStatus = $("select[name = paymentStatus]").val();
d.requested = $("select[name = requested]").val();
}
},
"columns": [
{data: 'id'},
{data: 'name'},
{data: 'email'},
{data: 'membership_no'},
{data: 'is_active'},
{data: 'varsity_session'},
{data: 'due_amount'},
{data: 'paid_amount'},
{data: 'created_at'},
{data: 'last_transaction_date'},
{data: 'action'},
],
"columnDefs": [
{"bSortable": false, "targets": [1, 6]},
{"searchable": false, "targets": [4, 6]}
],
lengthMenu: [[10, 50, 100, -1], [10, 50, 100, "All"]],
pageLength: 10,
"dom": 'Blfrtip',
buttons: [
{
extend: 'copy',
text: 'copy',
className: 'btn btn-primary',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'csv',
text: 'csv',
className: 'btn btn-warning',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'excel',
text: 'excel',
className: 'btn btn-danger',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'pdf',
text: 'pdf',
className: 'btn btn-success',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'print',
text: 'print',
className: 'btn btn-btn-info',
exportOptions: {
columns: 'th:not(:last-child)'
}
}
]
});
});
And my Static Html code
<div class="row">
<div class="col-lg-12">
<div class="table-responsive">
<table class="display compact dataTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Membership No</th>
<th>Status</th>
<th>Versity Session</th>
<th>Due Amount</th>
<th>Paid Amount</th>
<th>Created At</th>
<th>Last Transaction</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!-- /.col-lg-12 -->
</div>

Resources