Laravel Datatable Data Display Issue - laravel

Below is my controller code. I have seen data in console and network tab ajax call but it is not displaying in view page table. Can someone please help me on this. Please tell me what i am doing wrong in this.
I have checked with static data passed directly on ajax call but also static data is not displaying too. but when i pass any string as static then it will display each character from string in different columns.
$finaldata = array();
foreach($reportDetails as $agentReportColumnKey => $agentReportColumnValue){
$tempfinaldata = array();
$tempfinaldata['Customer Name'] = isset($agentReportColumnValue->name) ? $agentReportColumnValue->name : '-';
$tempfinaldata['Number'] = isset($agentReportColumnValue->tel) ? $agentReportColumnValue->tel : '-';
$tempfinaldata['Email'] = isset($agentReportColumnValue->email) ? $agentReportColumnValue->email : '-';
$tempfinaldata['DOB'] = isset($agentReportColumnValue->signUpQuestionDetails->birthDay) ? $agentReportColumnValue->signUpQuestionDetails->birthDay : '-';
$tempfinaldata['Debt Level'] = $agentReportColumnValue->debtLevel->sum('amountOwned') ? $agentReportColumnValue->debtLevel->sum('amountOwned') : '-';
$tempfinaldata['Total Debt'] = isset($agentReportColumnValue->quickSolution[0]->totalDebts) ? $agentReportColumnValue->quickSolution[0]->totalDebts : '-';
$tempfinaldata['Employment'] = isset($agentReportColumnValue->signUpQuestionDetails->EmpStatus) ? $agentReportColumnValue->signUpQuestionDetails->EmpStatus : '-';
$tempfinaldata['Living Arrangements'] = isset($agentReportColumnValue->signUpQuestionDetails->rentOrOwnHome) ? $agentReportColumnValue->signUpQuestionDetails->rentOrOwnHome : '-';
$tempfinaldata['Downloaded Date'] = isset($agentReportColumnValue->userSignInDate) ? date('d-m-Y', strtotime($agentReportColumnValue->userSignInDate)) : '-';
if(strtolower($agentReportColumnValue->zCaseType) == 'completed') {
$tempfinaldata['Completed Date'] = isset($agentReportColumnValue->userStatusUpdatedDate) ? date('d-m-Y', strtotime($agentReportColumnValue->userStatusUpdatedDate)) : '-';
} else {
$tempfinaldata['Completed Date'] = '-';
}
$tempfinaldata['Case Status'] = isset($agentReportColumnValue->zCaseType) ? $agentReportColumnValue->zCaseType : '-';
$tempfinaldata['Solution Type'] = isset($agentReportColumnValue->UserSolution->solutionType) ? $agentReportColumnValue->UserSolution->solutionType : '-';
$finaldata[] = $tempfinaldata;
}
$totalRecords = UserNames::select('count(*) as allcount')->count();
$totalRecordswithFilter = UserNames::select('count(*) as allcount')->where('name', 'like', '%' .$searchValue . '%')->count();
return [
'aaData' => $finaldata,
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordswithFilter,
];
Below is my view file code.
$('document').ready(function()
{
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type : 'POST',
url : '{{ route('report.full_report_ajax_data') }}',
//dataType: 'json',
cache: false,
success : function(result) {
//pass data to datatable
console.log(result); // just to see I'm getting the correct data.
$('#full_report').DataTable({
"searching": false, //this is disabled because I have a custom search.
//"aaData": [result], //here we get the array data from the ajax call.
"aaData": [result], //here we get the array data from the ajax call.
//"bProcessing": true,
"aoColumns": [
{ "sTitle": "Customer Name" },
{ "sTitle": "Number" },
{ "sTitle": "Email" },
{ "sTitle": "DOB" },
{ "sTitle": "Debt Level" },
{ "sTitle": "Total Debt" },
{ "sTitle": "Employment" },
{ "sTitle": "Living Arrangements" },
{ "sTitle": "Downloaded Date" },
{ "sTitle": "Completed Date" },
{ "sTitle": "Case Status" },
{ "sTitle": "Solution Type" },
] //this isn't necessary unless you want modify the header
//names without changing it in your html code.
//I find it useful tho' to setup the headers this way.
});
}
});
});

Related

Preserve record when InLineEditing JQGrid gives error when adding or changing

I am using InLineEditing JQGrid and when adding or changing a record, if it fails, the record disappears. I need to preserve these lines for the user to correct the wrong information and try to save the record again.
Below my snippet code
jQuery("#" + p_gridName).jqGrid('inlineNav', '#p' + p_gridName, {
edit : true, editicon : "ui-icon-pencil",
add : true, addicon : "ui-icon-plus",
save : true, saveicon : "ui-icon-disk", savetitle : "Salvar",
cancel : true, cancelicon : "ui-icon-cancel", canceltitle : "Cancelar",
editParams : {
keys : false, oneditfunc : null, successfunc : function (response) {
if (response != null && response.responseText != null) {
if (response.responseText.includes("OK")) {
alert(response.responseText);
reloadDataGrid(p_gridName, p_contentName, p_filtroGrid);
atualizaInfoStatusNavegacao('edit', valorChave, p_primaryKey, p_contentName);
return true;
} else {
alert(response.responseText);
return true;
}
}
}, afterrestorefunc: function (rowid) {
alert("after restore func");
return rowid;
}, restoreAfterError : false
},
addParams : {
useDefValues : true, addRowParams : {
successfunc : function (response) {
if (response.responseText.includes("OK")) {
alert(response.responseText);
reloadDataGrid(p_gridName, p_contentName, p_filtroGrid);
return true;
} else {
alert(response.responseText);
return true;
}
}
}
}
});
There is a option called restoreAfterError (see docs here), which by default is true. Set it to false in order to get the desired behavior.
This is a option (parameter) in editRow or saveRow.
EDIT
Your code should return true or better array with first value true/false and message like this
if (response != null && response.responseText != null) {
if (response.responseText.includes("OK")) {
alert(response.responseText);
reloadDataGrid(p_gridName, p_contentName, p_filtroGrid);
atualizaInfoStatusNavegacao('edit', valorChave, p_primaryKey, p_contentName);
return [true,''];
} else {
return [false, response.responseText];
}
} else {
return [false, 'no response from the server'];
}

How to store an object into database using laravel

Below is my Js, I used it to get data from a datatable
$("#mark_attendance").on("click", function(event) {
event.preventDefault();
var table = $("#attendance_table").DataTable();
let attendance_status = [];
$("select[name='attendance_status[]']").each(function() {
attendance_status.push($(this).val());
});
let attendance_date = [];
$("input[name='attendance_date[]']").each(function() {
attendance_date.push($(this).val());
});
var data = table
.rows()
.data()
.toArray();
data = data.map((item,i)=>{
return {
attendance_status: attendance_status[i],...item,
}
})
var attendance_data = data.map((item,i)=>{
return {
attendance_date: attendance_date[i],...item
}
})
// attendance_data.forEach(function(payload){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'post',
url: "/store/attendance",
data: {attendance_data: data},
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function() {
console.log("Error");
}
});
// });
});
Below is my controller
public function storeAttendance(Request $request)
{
$data = $request->all();
return response()->json('$data');
}
I get the below object in my console after clicking firing the even
{attendance_data: Array(3)}attendance_data: Array(3)
0: {attendance_status: "false", id: "1", employee_name: "Admin", department_id: "2"}
1: {attendance_status: "false", id: "2", employee_name: "User", department_id: "1"}
2: {attendance_status: "false", id: "3", employee_name: "Chinyere Lynda", department_id: "1"}
The simplest approach:
Define the name of your html inputs exactly the same as your model attributes
Go to the your Model and define the $fillable array, put there every attribute that you want to save here ( take a look here )
make a simple loop in your controller function that way :
$attendances = $request->all();
foreach($attendances as $attendance) {
Attendance::create($attendance);
}

How to set select2 (Ajax) default value

How to define select2 default AJAX value?
I've tried many but still cannot get it working.
Below is my code:
$("#qrcode_group_rowid").select2({
ajax: {
url: "app/qrcode/qrcode_group_select_service.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 50) < data.total_count
}
};
},
cache: true
},
placeholder: 'Please select',
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 0,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo (json) {
if (json.loading) {
return json.text;
}
var markup = json.group_name;
return markup;
}
function formatRepoSelection (json) {
return json.group_name;
}
and my JSON data:
{
"total_count": 897,
"items": [{"id": 901,"group_name": "TEST25-117"},{"id": 1,"group_name": "TEM117"}]
}
What am I doing wrong and how can I fix it?
You should send the following information in the PHP method (there may be a limitation of working with the IP address in eloquent)
/** #var Collection $btsNodes */
$btsNodes = BtsNode::where('node_code' , 'like' , '%'.$request->get('q').'%')
->get(['node_code']);
// ->toArray();
$items = $btsNodes->map(function ($item){
return [
'id' => $item['node_code'],
'node_code' => $item['node_code']
];
});
return ['items' => $items];

JsGrid Sorting not working

Following is part of my JsGrid code, which I think something is missing in order for me to sort my data like any other examples on Fiddle.
autoload: true,
inserting: false,
editing: false,
paging: true,
pageIndex: 1,
pageSize: 5,
pageLoading: true,
autoload: true,
filter: true,
sorting: true,
controller: {
loadData: function(filter) {
return $.ajax({
type: "GET",
url: BASE_URL,
data: filter,
dataType: "json",
cache: false
});
},
},
I have tried with sorting:"number".
Below logic of sorting on the basis of number
$("#Grid2").jsGrid({
height: "auto",
width: "100%",
filtering: false,
editing: false,
sorting: true,
paging: true,
autoload: true,
inserting: false,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(filter) {
var d = $.Deferred();
$.ajax({
cache: false,
type: 'GET',
url: "http://" + servername + ":" + portnumber + "/api,
data: filter,
dataType: "json",
success: function(data) {
filteredData = $.grep(data, function(item) {
//filtering logic
;
});
d.resolve(filteredData);
testdata = JSON.stringify(data);
$("#Grid2").jsGrid("sort", 1);
HistoricData = data;
},
error: function(e) {
console.log(e);
console.log(e.responseText);
var errorMsg = e.responseText;
var msg = errorMsg + " for this particular combination";
showError(msg);
$("#displayingHistoryValues").hide();
$("#ExportGrid2").hide();
$("#Grid2").hide();
d.resolve();
}
});
return d.promise();
}
},
fields: [{
title: "Value",
name: "MeasureValue",
type: "number",
width: "5%",
css: "custom-field",
sorting: true,
itemTemplate: function(value, item) {
if (item.MeasureValue != null && item.MeasureValue != '' && item.MeasureValue.trim().length > 0) {
var mesval = FormatValeur(item.MeasureUnit, item.MeasureValue);
return "<div>" + mesval + "</div>";
}
}
}, {
type: "control",
editButton: false,
deleteButton: false,
width: "5%"
}]
})
Another way to sort, get the filteredData or loaded data
and call onRefresing of JSGrid .
Way to sort JS grid on column after grid load :
onRefreshing: function (args) {
fundCodeList = [];
jsonNumLst = [];
jsonNANLst = [];
if(this._visibleFieldIndex(this._sortField) == -1
|| this._visibleFieldIndex(this._sortField)==1){
$.each(filteredData, function(inx, obj) {
if($.isNumeric(obj.fundCode)){
jsonNumLst.push(obj);
}else{
jsonNANLst.push(obj);
}
});
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
jsonNumLst.sort(sortByNumFCAsc);
jsonNANLst.sort(sortByNANFCAsc);
}else if(this._sortOrder == 'desc'){
jsonNANLst.sort(sortByNANFCDesc);
jsonNumLst.sort(sortByNumFCDesc);
}
if(jsonNumLst.length>0 || jsonNANLst.length>0){
filteredData = [];
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNumLst.length){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
}
}else if(this._sortOrder == 'desc'){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNANLst.length){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
}
}
}
if((filteredData.length>0) && filteredData.length==(jsonNumLst.length+jsonNANLst.length)){
$("#measureImportGrid3").data("JSGrid").data = filteredData;
//isSortGrid = false;
//saveEffectControlData = $('#saveEffectiveControlGrid').jsGrid('option', 'data');
}
}
//Ascending order numeric
function sortByNumFCAsc(x,y) {
return x.fundCode - y.fundCode;
}
//Ascending order nonnumeric
function sortByNANFCAsc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((x.fundCode > y.fundCode) ? 1 : -1 ));
}
//Descending order numeric
function sortByNANFCDesc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((y.fundCode > x.fundCode) ? 1 : -1 ));
}
//Descending order non-numeric
function sortByNumFCDesc(x,y) {
return y.fundCode - x.fundCode;
}
}

Semantic UI custom form validation with Ajax

I am trying to implement custom form validation rules for my username field, which should check the database for duplicated or not.
After Searching on the internet, I had write out some code, and it successful getting the response "true / false" from my server. But the fields in the form doesn't update as it should. Below was my javascript code.
$.fn.form.settings.rules.checkUsername = function(value) {
var res = true;
$.ajax({
async : false,
url: '<?= Yii::app()->createAbsoluteUrl('home/doCheckUsername') ?>',
type : "POST",
data : {
username : value
},
dataType: "json",
success: function(data) {
if (data.result == true) {
console.log(data.result);
return false;
} else {
console.log(data.result);
return true;
}
}
});
};
$('.ui.form').form({
username: {
identifier : 'username',
rules: [{
type : 'checkUsername',
prompt : 'Username Already Exists'
}]
}
// some other rules
}, {
inline : true,
on : 'blur',
onSuccess : function(){
//post to controller
}
});
The console.log showing me the correct result as I want, but I keep getting "Username Is Exist" as show at the picture
Semantic UI form Validation result
May I know where are the place I doing it wrong ?
Somehow, Added Async at the ajax solve the problem.
$.ajax({
async : false,
url: '<?= Yii::app()->createAbsoluteUrl('home/doCheckUsername') ?>',
type : "POST",
async: false,
data : {
username : value
},
dataType: "json",
success: function(data) {
if (data.result == true) {
console.log(data.result);
res = false;
}
}
});
Put result in the res variable and return the res variable after the ajax call !
Work for me :
$.fn.form.settings.rules.checkemail = function(value) {
var res = true;
$.ajax({
async : false,
url: '../php/email_exist.php',
type : "POST",
async: false,
data : {
email : value
},
success: function(data) {
console.log(data);
if (data == "0") {
console.log("OK");
res = true;
} else {
console.log("KO");
res = false;
}
}
});
return res;
};
$.fn.form.settings.rules.checkUsername = function(value) {
var res = true;
$.ajax({
async : false,
url: '<?= Yii::app()->createAbsoluteUrl('home/doCheckUsername') ?>',
type : "POST",
data : {
username : value
},
dataType: "json",
success: function(data) {
if (data.result == true) {
//console.log(data.result);
//return false;
**value = 0;**
} else {
//console.log(data.result);
//return true;
**value = 1;**
}
}
});
**return (value == 1 )? true : false;**
};
$('.ui.form').form({
username: {
identifier : 'username',
rules: [{
type : '**checkUsername[value]**',
prompt : 'Username Already Exists'
}]
}
// some other rules
}, {
inline : true,
on : 'blur',
onSuccess : function(){
//post to controller
}
});

Resources