Laravel Datatables empty collection error - javascript

I'm using Laravel Datatables package to show Ajaxified tables.
I'm getting an error when the collection i want to show in my table is empty, the error is:
ErrorException in CollectionEngine.php line 46: array_keys() expects
parameter 1 to be array, null given
My controller contains two simple functions
// get the view
public function getItems() {
return view('someview');
}
// get data for datatables
public function getItemsdata() {
$data = DataModel::all();
return Datatables::of($data)->make(true);
}
When $data is not empty, everything works just fine but if it is empty, I get the error! how can i fix this? any ideas?

I think you can use the isEmpty() function of laravel
public function getItemsdata() {
$data = DataModel::all();
if($data->isEmpty()){ //I think laravel has isEmpty() function
return 'error!'; //throw exception here
}else{
return Datatables::of($data)->make(true);
}
}

Related

Error when laoding datatable from JSON

I'm developing a project where I fill an HTML table using datatables and a JSON returned from my server, which originally is a list of a class.
The code is the following one for each element:
Table HTML:
<table id="tablaDetalle2" class="display" role="grid" aria-describedby="example2_info">
<thead>
<tr>
<th>id</th>
<th>idFlight</th>
<th>idSample</th>
<th>import</th>
</tr>
</thead>
<tbody>
</table>
Javascript:
$('#tablaDetalle2').DataTable({
"bProcessing": true,
"sAjaxSource": "#Url.Action("Detalle","Muestra", new {idExp = 1, descrExp="abc"})"
});
ServerCode:
public ActionResult Detalle(int idExp, string descrExp)
{
List<Models.Muestra_Detalle> aaData = new List<Models.Muestra_Detalle>(); //Returns a list of the data
aaData = Manager.MuestraManager.Cargar_Detalle(idExp);
var jsonSerializer = new JavaScriptSerializer();
var JsonFinal = jsonSerializer.Serialize(aaData);
try
{
return Json(new { JsonFinal }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{ return null; }
}
The object JsonFinal returned has the following structure:
[{"id":"1","idFlight":1,"idSample":3217.5,"import":0}]
But I get the following error:
Unhandled exception at line 188, column 47 in
http://localhost:61298/Content/DataTables/jquery.dataTables.min.js
0x800a138f - JavaScript runtime error: Unable to get property 'length' of undefined or null reference
For instance, if I declare a hardcoded variable:
var data = new[] { "id:A", "idFlight:B", "idSample:C", "import:D" };
No error shows up, even though the content defined in the variable data and how it's shown in the table doesn't match.
I've tried so many ways to do it, some says it's just no data to show in the table, this seems the best possible approach once the issue is solved.
The biggest difference when hardcoding a the variable returned to the datatables is that the variable data is an object with 4 different strings, and the result of using JsonSerializer It's just like one string, I don't really know.
ÛPDATE
Renamed the JsonFinal to aaData, some error different pops ups, will try what some of you said and report back with more details.
New code from the server:
public ActionResult Detalle(int idExp, string descrExp)
{
ViewBag.Exp = descrExp;
List<Models.Muestra_Detalle> azaData = new List<Models.Muestra_Detalle>();
aaData = Manager.MuestraManager.Cargar_Detalle(idExp);
var jsonSerializer = new JavaScriptSerializer();
var aaData = jsonSerializer.Serialize(azaData);
//string data2 = JsonFinal.Replace("\\", "");
//var data = new[] { "id:A", "idgasto:B", "ImpGasto:C", "idMuestra:D" };
return Json(new { aaData }, JsonRequestBehavior.AllowGet);
}
New error : DataTables warning: table id=tablaDetalle2 - Requested unknown paramter 'id' for row 0, column 0. For more information about this error, please see https://datatables.net/tn/4.
Already went over there, couldnt get anything out.
It's like it can't find the column id in the returned JSON as it becomes null in the table.
Try returning your json object directly without using serializer. For example
public ActionResult Detalle(int idExp, string descrExp)
{
List<Models.Muestra_Detalle> aaData = new List<Models.Muestra_Detalle>(); //Returns a list of the data
aaData = Manager.MuestraManager.Cargar_Detalle(idExp);
try
{
return Json(aaData , JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{ return null; }
}
Alright, I still don't render the table correctly based on the JSON information but I managed to solve the issue....
The method I'm using sAjaxSource must return the object JSON from the server side named as aaData, now I have a problem as no matter what I send to the client, it will always take the first column with the value " and the rest of columns as null, but will ask another question for that.

Returning a JSON object from a slim php

I'm trying to return a JSON object from a call to a slim PHP function. It returns the object like this:
if (count > 0) {
echo json_encode(array("status" => "greater"));
} else {
echo json_encode(array("status" => "lesser"));
}
In my javascript I call this slim function using a service:
$scope.statusResults = service.isGreater();
console.log($scope.statusResults);
but what I get back in the console is: e {$$state: Object}
If I drill down into e, I find $$state : Object
which I can drill down into to get: status:1 value:Object and one last time to finally get to status:"greater"
I have no idea what $$state is or why it returns this way. I wanted it to return as a simple JSON object and just be {status: "greater"}. Is there a way to get it to return like that? If not, how do I access status?
Thanks!

Jquery send data to controller method from $().Load()

First try to relate the things.
I have a dynamic created div which I was loading from $().Load()
something like this
$(elem).load("BarChart");
Note: elem id dynamically created div at the same moment
untill this all working fine but now I want to send selected Data
something like this
$(elem).load("BarChart",{Values: values});
Note: BarChart is Partial View. which is calling Controller Method but not able to find the values passed from load
controller Method
public ActionResult BarChart(List<String> Values)
{
foreach (var v in Values)
{
lstPointSeries = Utility.GetPointSeries(Session["DbName"].ToString(), Session["AccountGroupName"].ToString(), null, AggregrationType.Total, v, null);
}
ViewBag.pointSeries = lstPointSeries;
return PartialView();
}
Note: Values is null
EDIT:
var values are list of selected checkbox from UI. like this
something like this
values = ["first","second","third","fourth"];
var values = $('input:checkbox:checked.XAxisrowCheckbox').map(function () {
return $(this).closest('td').next().text();
}).get();
I tried your code, and it works fine
Try this:
url = urlHelper.CommonHelper("", "About", "TestAction");
$("#TestDivId").load(url, { Values: ["aaa","bbb"] });
public ActionResult TestAction(List<string> Values) { return View(); }

Issue trying to preform a delete with php and angular

I am trying to preform a delete with angular and php. I am pretty sure that my php is right.
But i am not able to delete. In my console log it says that my deletion was succesfull but when looking in the table I still see the recored.
Upon further inspection with debugger in chrome I see dat my parameter index is undefined -> http://gyazo.com/88b6dcf9d4c03a1fc9dd235303b20a8f
(part of) My HTML code:
<md-button class="md-primary" ng-click="delete_task(task.id)">Delete</md-button>
(part of) My app.js file:
/** function to delete a task from list referencing php **/
$scope.delete_task = function(index) {
debugger;
$http.post('db.php?action=delete_task',
{
'task_index' : index
}
)
.success(function (data, status, headers, config) {
// here we also replace how to get the user
getTaskFunction(
/* success function */
function(data) {
$scope.taskInfo = data;
console.log("The taks have been reloaded" , $scope.taskInfo);
},
/* error function */
function()
{
alert("Server load failed");
}
);
console.log('Deletion was succesfull');
})
.error(function(data, status, headers, config) {
console.log("You were NOT succesfull in deleting a task");
}
);
(part of) My PHP code:
<?php
include('config.php');
switch($_GET['action']) {
case 'get_ProjectType_Info' :
get_ProjectType_Info();
break;
case 'add_task' :
add_task();
break;
case 'get_Location_Info' :
get_Location_Info();
break;
case 'get_Task_Info' :
get_Task_Info();
break;
case 'delete_task' :
delete_task();
break;
}
/** Function to delete a task **/
function delete_task() {
$data = json_decode(file_get_contents("php://input"));
$index = $data->task_index;
echo ($index);
//print_r($data);
$del = mysql_query("DELETE FROM tblTask WHERE id = ".$index);
if($del)
return true;
return false;
}
I am not sure how to proceed from this point on.
It should be better not use querystring variables together with post variables as you're doing. Create a complete object on javascript statement in order to have something like this:
{
'task_index' : index,
action: 'delete_task'
}
And then you should threat this object data inside you switcher.
It would be great if you adopt some practices that take the code cleaner and easier to understand.
First thing of all, you should test your delete_task method. To make it successfully I suggest you to get the variables calling file_get_contents("php://input")) into the switch and passing them as method parameters. Make it this way:
<?php
// ...
// Receive id you have already collected
function delete_task($task_id){
$del = mysql_query("DELETE FROM tblTask WHERE id = ".$task_id);
if($del) return true;
return false;
}
// test that method
function test_delete(){
$ret = delete_task(4); // test with valid and invalid ids
}
?>
Obviously this is not a beautiful way to test methods and you should consider using any test framework for unit tests. But it's important to build methods in a way that you can change parameters and observe its behavior. Once you are assured that this method (the more critic one in this scenery) is working, you can go down one level on stack and check if your switcher is working well. At this time you can test your endpoint using Postman for Chrome, as an example.

MongoDB query criteria not working correctly Meteor / JavaScript

I have a Products collection with an attribute called "productCode". I am trying to write a server-side query to return a product based on the productCode attribute, but I keep getting a "cannot read property 'propertyCode' of undefined" error.
Here is my method call:
Meteor.call('findProduct', searchVal, function(error, a) {
if(error) {
alert(error.reason)
} else {
console.log('search success!');
}
});
Here is my methods.js code that is giving me that error:
'findProduct': function(searchVal, a) {
a = Products.findOne({productCode: searchVal});
return a; //return the product of interest
}
Error: Exception in delivering result of invoking 'findProduct': TypeError: Cannot read property 'productCode' of undefined
However, if I hard code in the product code, it works:
'findProduct': function(searchVal, a) {
a = Products.findOne({productCode: 9021073});
return a; //this will return the product
}
In my terminal console, this works as well:
db.products.findOne({productCode: 291105300});
Any ideas what I might be doing wrong?
Ah - the reason is initially a string. I converted it to an Integer using parseInt and it worked!

Categories