Pass JSON data (by using Ajax ) to table in View Laravel - ajax

I am new to Laravel and trying to self learn the same for inhouse project.
Trying to pass json data to table for showing the data in the same. Data received in json is ok but not able to put the same in Table
Controller:
public function getmilkrecordforbid(Request $req)
{
$bidformilk = $req->bidformilkrecord;
$bmilkrecord = buffalomilkrecord::where('buffaloID', '=', $bidformilk)-
>get();
return ($bmilkrecord);
}
web.php
Route::post('/getmilkrecordforbid'[BuffalodataController::class,'getmilkrecordforbid'])
ajax file
$('#selectid').on('change', function() {
var bidformilkrecord = $('#selectid').val();
$.ajax({
url : '/getmilkrecordforbid',
dataType : "json",
method : "POST",
data : {'bidformilkrecord': bidformilkrecord, "_token":"{{
csrf_token()}}"},
success: function(data){
console.log(data)
console.log(data.length)
},
});
});
console.log
(4) [{…}, {…}, {…}, {…}]0: {id: 5, buffaloID: 'Buffalo-02', date: '2020-12-15', milkmorning: '5.00', milkevening: '6.00', …}1: {id: 6, buffaloID: 'Buffalo-02', date: '2020-12-16', milkmorning: '5.00', milkevening: '5.00', …}2: {id: 7, buffaloID: 'Buffalo-02', date: '2020-12-17', milkmorning: '5.00', milkevening: '5.00', …}3: {id: 8, buffaloID: 'Buffalo-02', date: '2020-12-18', milkmorning: '5.00', milkevening: '5.00', …}length: 4[[Prototype]]: Array(0)
Table html
<table id="milksummery" class="table table-bordered table-hover table"
style="width:100%">
<thead>
<tr>
<th>Date</th>
<th>Morning Milk</th>
th>Evening Milk</th>
<th>Total Milk</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Your guidance will really help me.......

You just need to manipulate the DOM on the success event. We are getting the first tbody element and adding more elements to it.
Here it is your code with the updated DOM.
$('#selectid').on('change', function() {
var bidformilkrecord = $('#selectid').val();
$.ajax({
url : '/getmilkrecordforbid',
dataType : "json",
method : "POST",
data : {
'bidformilkrecord': bidformilkrecord,
"_token": "{{ csrf_token() }}"
},
success: function(data){
console.log(data)
console.log(data.length)
let tbody = document.getElementsByTagName("tbody")[0];
for (let i = 0; i < data.length; i++) {
let milkSummeryRow = tbody.insertRow();
let dateCell = milkSummeryRow.insertCell();
let dateText = document.createTextNode(data[i]['date']);
dateCell.appendChild(dateText);
let milkMorningCell = milkSummeryRow.insertCell();
let milkMorningText = document.createTextNode(data[i]['milkmorning']);
milkMorningCell.appendChild(milkMorningText);
let milkEveningCell = milkSummeryRow.insertCell();
let milkEveningText = document.createTextNode(data[i]['milkevening']);
milkEveningCell.appendChild(milkEveningText);
let milkTotalCell = milkSummeryRow.insertCell();
let milkTotalText = document.createTextNode(parseFloat(data[i]['milkmorning']) + parseFloat(data[i]['milkevening']));
milkTotalCell.appendChild(milkTotalText);
}
},
});
});

Related

How to get the data for a DataTable from the Controller to View using Ajax

In my main controller, I have a function that gets the data from the database, formats it and output it as JSON. My problem now is how to display this data to the DataTable. Most examples I read have the data saved from a different file from the controller. I would for the data to be from a function in the controller. How do I call that function?
View (SampleView.php)
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>EmpID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$( document ).ready(function() {
var table = $('#example').DataTable( {
"ajax": "main/getDataFunction",
// "ajax": "getDataFunction",
// "ajax": "<?php echo base_url()."main/getDataFunction"; ?>",
// "ajax": { url: 'main/getDataFunction', type: 'POST' },
"bPaginate":true,
"bProcessing": true,
"pageLength": 10,
"columns": [
{ mData: 'EmpID' } ,
{ mData: 'FirstName' },
{ mData: 'LastName' }
]
});
});
</script>
Controller (Main.php)
function getDataFunction() {
$sampleData = $this->db->getSampleData();
$data = array();
foreach($sampleData as $key) {
array_push($data, array("EmpID" => $key->empID,
"FirstName" => $key->firstName,
"LastName" => $key->lastName));
}
$results = array("sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData"=>$data);
echo json_encode($results);
}
Output of echo json_encode($results)
{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":[{"EmpID":"1","FirstName":"JOHN","LastName":"DOE"}]}
I am not sure about DataTable but what you can do is you can use eval() to evaluate json data first and then fetch your json response values into view.
Old way which I knew is —
$.ajax(function() {
type : 'get', // or 'post',
data : {key:value},
dataType : 'json',
success : function(response){
var html_data = response.eval(); // this will serialize your data object
$('selector').val(html_data.name);
// $('selector').val(html_data.sEcho); as per your output of the code.
// or
$('selector').html(html_data);
}
});

Passing data to controller and changing the view

I have the following scenario:
I have a table with a list of book. Now, when I click on the selected rows, I want to send the book titles to the rental controller so that the controller can then call the appropriate view pass the book titles.
Here's the code for the table view:
<button id="checkoutButton">Checkout</button>
<table id="books" class="table table-bordered table-hover">
<thead>
<tr>
<th>Book</th>
<th>Category</th>
<th>Author</th>
<th>Registration Number</th>
<th>Volume</th>
<th>Number In Stock</th>
<th>Number Available</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
}
#section Scripts{
<script>
$(document).ready(function () {
var titles = [];
var table = $("#books").DataTable({
ajax: {
url: "/api/books",
dataSrc: ""
},
columns: [
{
data: "title"
},
{
data: "categoryId"
},
{
data: "registrationNumber"
},
{
data: "volume"
},
{
data: "numberInStock"
},
{
data: "numberAvailable"
},
{
data: "author"
}
]
});
$('#checkoutButton').click(function () {
var obj = table.rows('.selected').data();
if (obj.length == 0)
console.log("No row selected");
else {
for (var i = 0; i < table.rows('.selected').data().length; i++) {
console.log(table.rows('.selected').data()[i].title);
titles.push(table.rows('.selected').data()[i].title);
}
$.ajax({
url: "/Rental/print",
contentType: 'application/json',
method: "POST",
data: JSON.stringify({ titles })
})
}
});
And here's the controller:
public ActionResult print(Object [] titles)
{
for(var i = 0; i < titles.Length; i++)
{
Debug.WriteLine(titles[i]);
}
return View("New");
}
I haven't passed the title to the view yet because the view is not rendering at all. I have verified that the controller does get the data but it does not navigate to the "New.html". Although, if I manually navigate to this page, it does render. So, I am really not sure what I am doing wrong here.
I will very much appreciate if you can point me to the right direction.
Note: I have not included the js code which selects multiple rows because I wanted to keep the code simple. Let me know if I need to show that too.

ajax is not accessing to my button inside datatable

I want to access to my button inside datatable which is inside of my modal, but when I want to access it wont load any alert , ajax url or whatever thing even If I change id or class of "a" tag. how can I fix it? this ajax I know it wont load and error in console, but it also show it..
ajax
$(function(event) {
URL_GET_VIEW_SEARCH_PRODUCT = BASE_URL + 'sale/sales/getViewSearch';
URL_GET_DATATABLE = BASE_URL + 'sale/sales/datatable';
URL_SEARCH_PRODUCT = BASE_URL + 'sale/sales/search_product';
$('#btn-search').click(function (e) {
BootstrapDialog.show({
title: 'Search Product',
message: function(dialog) {
var $message = $('<div></div>');
var pageToLoad = dialog.getData('pageToLoad');
$message.load(pageToLoad);
return $message;
},
data: {
pageToLoad: URL_GET_VIEW_SEARCH_PRODUCT
},
onshown: function(dialog){
$('#example').DataTable({
lengthChange: false,
responsive: true,
ajax: {
url: URL_GET_DATATABLE,
type: 'POST',
},
columnDefs: [{
targets: 4,
data: null,
defaultContent: "<a href='#'><span class='glyphicon glyphicon-plus'></span></a>"
}],
});
}
});
});
$('#search').typeahead({
source: function (query,process) {
$.ajax({
url: URL_SEARCH_PRODUCT,
type: 'POST',
data: {query: query},
dataType: 'json',
async: true,
success: function (data) {
console.log(data);
process(data);
}
});
}
});
$('#example tbody').on('click', 'a', function(event) {
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
});
});
table view
<table id="example" class="table table-bordered table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th>Code</th>
<th>Description</th>
<th>Stock</th>
<th>Price</th>
<th></th>
</tr>
</thead>
</table>

DataTables jquery.dataTables.min.js:181 Uncaught TypeError: Cannot read property 'length' of undefined

I can't specify what/where is the problem, here is my code :
HTML :
<table id="companies" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th class="center">
Id
</th>
<th>RegNo</th>
<th>Name</th>
<th class="hidden-480">Industry</th>
<th class="hidden-phone">
Size
</th>
<th class="hidden-480">LineOfDefence</th>
<th>Address</th>
</tr>
</thead>
</table>
Server side :
var result = new
{
rows = (from company in db.Company.ToList()
select new
{
id = company.CompanyId,
RegNo = company.RegestrationNumber,
Name = company.Name,
Industry = company.IndustryType.Name,
Size = company.CompanySize.Name,
LineOfDefence = company.LineOfDefence.Name,
Address = company.Address
}).ToArray()
};
return Json(result, JsonRequestBehavior.AllowGet);
and here is my Ajax Call :
<script>
$(document).ready(function ()
{
$('#companies').DataTable( {
"ajax": {
url: "/Company/GetCompanyGrid",
type: "GET",
dataType: "json"
}
});
});
</script>
I'm getting this error : "jquery.dataTables.min.js:181 Uncaught TypeError: Cannot read property 'length' of undefined"
note : I'm using jquery-1.12.3.js & DataTables 1.10.12.
Any help would be appreciated .
finally I've figured out the problem :
first : datatables expects specific format, so I changed my server side code like this :
var result = new
{
**draw = 1,
recordsTotal = db.Company.ToList().Count,
recordsFiltered = db.Company.ToList().Count,**
data = (from company in db.Company.ToList()
select new
{
Id = company.CompanyId,
RegNo = company.RegestrationNumber,
Name = company.Name,
Industry = company.IndustryType.Name,
Size = company.CompanySize.Name,
LineOfDefence = company.LineOfDefence.Name,
Address = company.Address,
}).ToArray()
};
return Json(result
, JsonRequestBehavior.AllowGet);
second : I've added these lines to my script
<script>
$(document).ready(function ()
{
$('#companies').DataTable( {
"ajax": {
url: "/Company/GetCompanyGrid",
type: "GET",
dataType: "json"
},"columns": [
{ "data": "Id" },
{ "data": "RegNo" },
{ "data": "Name" },
{ "data": "Industry" },
{ "data": "Size" },
{ "data": "LineOfDefence" },
{ "data": "Address" },
{ "data": "Logo" },
{ "data": null },
]
});
});
</script>
and now it's working perfectly.
Datatables expects the returned json to be in a specific format, as per the documentation - see the 'Returned data' section.
Your json should look something like this:
return Json(new
{
param.draw,
recordsTotal = result.Count,
recordsFiltered = result.Count,
data = result
}, JsonRequestBehavior.AllowGet);
The error is probably a result of datatables looking for a field that isn't present. Note that the draw value is sent in the original GetCompanyGrid() request, you don't need to generate it yourself.

Passing Id from javascript to Controller in mvc3

How to pass Id from javascript to Controller action in mvc3 on ajax unobtrusive form submit
My script
<script type="text/javascript">
$(document).ready(function () {
$("#tblclick td[id]").each(function (i, elem) {
$(elem).click(function (e) {
var ID = this.id;
alert(ID);
// var url = '#Url.Action("Listpage2", "Home")';
var data = { Id: ID };
// $.post(url,data, function (result) {
// });
e.preventDefault();
$('form#myAjaxForm').submit();
});
});
});
</script>
the how to pass Id on using $('form#myAjaxForm').submit(); to controller
instead of
$.post(url,data, function (result) {
// });
My View
#using (Ajax.BeginForm("Listpage2", "", new AjaxOptions
{
UpdateTargetId = "showpage"
}, new { #id = "myAjaxForm" }))
{
<table id="tblclick">
#for (int i = 0; i < Model.names.Count; i++)
{
<tr>
<td id='#Model.names[i].Id'>
#Html.LabelFor(model => model.names[i].Name, Model.names[i].Name, new { #id = Model.names[i].Id })
<br />
</td>
</tr>
}
</table>
}
</td>
<td id="showpage">
</td>
I would avoid using the Ajax Beginform helper method and do some pure handwritten and Clean javascript like this
<table id="tblclick">
#foreach(var name in Model.names)
{
<tr>
<td id="#name.Id">
#Html.ActionLink(name.Name,"listpage","yourControllerName",
new { #id = name.Id },new { #class="ajaxShow"})
</td>
</tr>
}
</table>
<script>
$(function(){
$(".ajaxShow")click(function(e){
e.preventDefault();
$("#showpage").load($(this).attr("href"));
});
});
</script>
This will generate the markup of anchor tag in your for each loop like this.
<a href="/yourControllerName/listpage/12" class="ajaxShow" >John</a>
<a href="/yourControllerName/listpage/35" class="ajaxShow" >Mark</a>
And when user clicks on the link, it uses jQuery load function to load the response from thae listpage action method to the div with id showPage.
Assuming your listpage action method accepts an id parameter and returns something
I am not sure for $.post but I know window.location works great for me.
Use this instead and hopefully you have good results :)
window.location = "#(Url.Action("Listpage2", "Home"))" + "Id=" + ID;
replace $('form#myAjaxForm').submit(); with this code and nothing looks blatantly wrong with your jscript.
Just use a text box helper with html attribute ID.
#Html.TextBox("ID")
You can do this too:
var form = $('form#myAjaxForm');
$.ajax({
type: "post",
async: false,
url: form.attr("action"),
data: form.serialize(),
success: function (data) {
// do something if successful
}
});

Resources