I have a Jquery grid that I know the success method is being executed and my grid will load, but with no data. I get the column headers but no results. When I look at the browser developer tools, (IE, Chrome), I am not getting any errors. If I put an alert message in the success of the Jquery grid, it will display. What am I missing? This is an MVC application.
content page:
#{ ViewBag.Title = "Workflow Dashboard";
}
<div>
#section scripts {
<script src="#Url.Content("~/Scripts/i18n/grid.locale-en.js")" type="text/javascript"></script>
#*<script src="#Url.Content("~/Scripts/jquery-2.1.1.min.js")" type="text/javascript"></script>*#
<script src="#Url.Content("~/Scripts/jquery.jqGrid.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/CPQ/Dashboard.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/CPQ/Permissions.js")" type="text/javascript"></script>
}
<div id="hiddenFields">
<input id="UserTypeID" type="hidden" value="#ViewBag.User.UserTypeID" />
</div>
#if (ViewBag.User.UserTypeID == (int)CPQ.Models.UserType.Administrator ||
ViewBag.User.UserTypeID == (int)CPQ.Models.UserType.CTM ||
ViewBag.User.UserTypeID == (int)CPQ.Models.UserType.CZM ||
ViewBag.User.UserTypeID == (int)CPQ.Models.UserType.GM ||
ViewBag.User.UserTypeID == (int)CPQ.Models.UserType.BDM)
{
<h3>#ViewBag.Title</h3>
<div class="row">
<div class="col-sm-12">
<table id="gridWorkflowDashboard"></table>
<div id="gridpager"></div>
</div>
</div>
<hr />
}
<h3>Recent</h3>
<div class="row">
<div class="col-sm-12">
#*<div id="gridRecentDashboard"></div>*#
<table id="gridRecentDashboard"></table>
</div>
</div>
</div>
Layout Page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>#ViewBag.Title - Commercial Price Quote Tool</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
<link href="#Url.Content("~/Scripts/jsgrid-1.5.3/jsgrid.min.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Scripts/jsgrid-1.5.3/jsgrid-theme.min.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Scripts/jquery-ui-1.12.1/jquery-ui.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-ui-1.12.1/jquery-ui.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jsgrid-1.5.3/jsgrid.min.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/ui.jqgrid.css")" rel="stylesheet" type="text/css"/>
<script src="#Url.Content("~/Scripts/Common.js")" type="text/javascript"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Commercial Price Quote Tool", "Index", "Search", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Dashboard", "Index", "Dashboard")</li>
<li>#Html.ActionLink("Customer Search", "Index", "Search")</li>
<li class="_admin" style="display:none;">#Html.ActionLink("Users", "Index", "Users")</li>
<li class="_admin" style="display:none;">#Html.ActionLink("Management", "Index", "Management")</li>
<li class="_admin"> <a class="navbar-header" href="https://one.web.ppg.com/na/refinish/coll/commcoatings/Contracts/CPQt%20Training%20Presentation,%203-4-19.pdf" target="_blank">Help</a></li>
#*<li>#Html.ActionLink("Z Price Editor", "Index", "ZPriceEditor")</li>*#
</ul>
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - Commercial Price Quote Tool</p>
</footer>
</div>
<div class="modal fade" id="loadingModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Alert</h4>
</div>
<div class="modal-body" id="loadingModalBody">
</div>
#*<div class="modal-footer"></div>*#
</div>
</div>
</div>
</body>
</html>
Dashboard.js:
var colNames = ["CTSID", "Customer", "Terr", "Zone Manager", "Status", "Version", "Workflow Step", "Expiration Date"];
var cols = [
{ label: 'CTSID', index: 'CTSID', name: 'CTSID', align: 'left' },
{ label: 'Customer', index: 'CustomerName', name: 'CustomerName', align: 'left' },
{ label: 'Terr', index: 'Territory', name: 'Territory', align: 'left' },
{ label: 'Zone Manager', index: 'CZMNanme', name: 'CZMNanme', align: 'left' },
{ label: 'Status', index: 'StatusName', name: 'StatusName', align: 'left' },
{ label: 'Version', index: 'VersionNumber', name: 'VersionNumber', align: 'left' },
{ label: 'Workflow Step', index: 'WorkflowName', name: 'WorkflowName', align: 'left' },
{ label: 'Expiration Date', index: 'EffectiveEndDate', name: 'EffectiveEndDate', align: 'left' }
];
var grid = $("#gridWorkflowDashboard");
var actionUrl = 'Dashboard/GetUserWorkflowDashboard';
var page = 1;
$(function () {
//Initialize jqgrid
$("#gridWorkflowDashboard").jqGrid({
dataType: 'local',
//type: 'GET',
colName: colNames,
colModel: cols,
sortname: 'EffectiveEndDate',
sortorder: 'asc',
rowList: [10, 25, 100],
height: 'auto',
pager: $('#gridpager'),
rowNum: 12,
gridview: true
});
});
$(document).ready(function () {
//page load call loadGrid()
loadGrid();
});
function loadGrid() {
var pCTSID = '';
var pCustomerName = '';
var pCZMName = '';
var pEffectiveEndDateModified = '';
var pStatusName = '';
var pTerritory = '';
var pVersionInformation = '';
var pWorkflowName = '';
var data = { CTSID: pCTSID, CustomerName: pCustomerName, CZMName: pCZMName, effectiveEndDateModified: pEffectiveEndDateModified, StatusName: pStatusName, Territory: pTerritory, VersionInformation: pVersionInformation, WorkflowName: pWorkflowName };
//var grid = $("#gridWorkflowDashboard");
$.ajax(actionUrl, {
contentType: 'application/json',
type: 'GET',
dataType: 'json',
data: JSON.stringify(data),
success: function (result) {
grid.clearGridData();
grid.jqGrid('setGridParam',
{
datatype: 'local',
data: result
}).trigger("reloadGrid");
},
error: function () {
DialogMessage = "Failed to Load Dashboard. Please Contact IT Support";
var VPDialogoptions = {
header: "Error",
message: DialogMessage,
dialogType: 'Close'
};
}
});
}
Controler Method:
public JsonResult GetUserWorkflowDashboard(string CTSID, string CustomerName, string CZMName, string effectiveEndDateModified,
string StatusName, string Territory, string VersionInformation, string WorkflowName)
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "[CPQ].[spGetUserWorkflowDashboard]"; //this sp also calls spCheckActiveQuotes
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = CurrentUser.UserID;
if (CTSID != "" && CTSID != null)
{
cmd.Parameters.Add("#CTSID", SqlDbType.VarChar).Value = CTSID;
}
if (CustomerName != "")
{
cmd.Parameters.Add("#CustomerName", SqlDbType.VarChar).Value = CustomerName;
}
if (CZMName != "")
{
cmd.Parameters.Add("#CZMName", SqlDbType.VarChar).Value = CZMName;
}
if (effectiveEndDateModified != "" && effectiveEndDateModified != null)
{
cmd.Parameters.Add("#effectiveEndDate", SqlDbType.Date).Value = Convert.ToDateTime(effectiveEndDateModified).ToShortDateString();
}
if (StatusName != "")
{
cmd.Parameters.Add("#StatusName", SqlDbType.VarChar).Value = StatusName;
}
if (Territory != "")
{
cmd.Parameters.Add("#Territory", SqlDbType.VarChar).Value = Territory;
}
if (VersionInformation != "")
{
cmd.Parameters.Add("#VersionInformation", SqlDbType.VarChar).Value = VersionInformation;
}
if (WorkflowName != "")
{
cmd.Parameters.Add("#WorkflowName", SqlDbType.VarChar).Value = WorkflowName;
}
DataSet ds = CommonDAL.ExecuteDataSet(cmd, CommonDAL.DataBaseName.RefinAgree);
DataTable dt = ds.Tables[0];
var DashboardList = new List<DashboardDTO>();
foreach (DataRow dr in dt.Rows)
{
var dash = new DashboardDTO();
dash.AccountNumbers = dr["AccountNumbers"].ToString();
dash.CTSID = Convert.ToInt32(dr["CTSID"]);
dash.CustomerName = dr["CustomerName"].ToString();
dash.Address1 = dr["Address1"].ToString();
dash.Address2 = dr["Address2"].ToString();
dash.City = dr["City"].ToString();
dash.State = dr["State"].ToString();
dash.Zip = dr["Zip"].ToString();
dash.Phone = dr["Phone"].ToString();
dash.Fax = dr["Fax"].ToString();
dash.Territory = dr["Territory"].ToString();
dash.CountryID = Convert.ToInt32(dr["CountryID"]);
dash.CountryDesc = dr["CountryDesc"].ToString();
dash.CZMID = Convert.ToInt32(dr["CZMID"]);
dash.CZMName = dr["CZMName"].ToString();
dash.StatusID = Convert.ToInt32(dr["StatusID"]);
dash.StatusName = dr["StatusName"].ToString();
dash.StatusDescription = dr["StatusDescription"].ToString();
dash.VersionNumber = dr["VersionNumber"].ToString();
dash.VersionID = Guid.Parse(dr["VersionID"].ToString());
dash.VersionInformation = dash.StatusName + " - " + dash.VersionNumber;
dash.WorkflowID = Convert.ToInt32(dr["WorkflowID"]);
dash.WorkflowName = dr["WorkflowName"].ToString();
dash.EffectiveEndDate = Convert.ToDateTime(dr["EffectiveEndDate"].ToString()).ToShortDateString();
//.Date.ToString("MM/dd/yyyy");
DashboardList.Add(dash);
}
return Json(DashboardList.ToArray(), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
string ExceptionMessage = ex.Message;
Console.Write(ExceptionMessage);
return null;
}
}
Your grid setup seems not correct.
You should set datatype='json'
You missed the url in the setup from where the data comes.
Note that javaScript is case sensetive - dataType is different from datatype. In jqGrid a datatype is used.
In order to get data from server maybe your setup should look like this:
var grid = $("#gridWorkflowDashboard");
var actionUrl = 'Dashboard/GetUserWorkflowDashboard';
var page = 1;
$(function () {
//Initialize jqgrid
$("#gridWorkflowDashboard").jqGrid({
datatype: 'json',
url: actionUrl,
page : page,
//type: 'GET',
colName: colNames,
colModel: cols,
sortname: 'EffectiveEndDate',
sortorder: 'asc',
rowList: [10, 25, 100],
height: 'auto',
pager: $('#gridpager'),
rowNum: 12,
gridview: true
});
Related
I am using Datatables to create Highcharts. Everything functions as intended, however I am not sure how to extract the X axis title from Column 1. (Data1, Data2, Data3, Data4, Data5 etc.). I am not sure what am I missing in my code. Any advice would be appreciated because I don't know much about Javascript. Thanks in advance.
The chart should look like this.
See screenshot below.
Link to code - http://live.datatables.net/muvoyacu/2/edit
$(document).ready(function() {
var table = $("#example_full2").DataTable({
searching:false,
lengthChange: false,
ordering: false,
info: false,
paging: false,
} );
//var salary = getSalaries(table);
var salary = getRow(table,0);
var salary2 = getRow(table, 1);
var salary3 = getRow(table, 2);
var salary4 = getRow(table, 3);
var salary5 = getRow(table, 4);
// Declare axis for the column graph
var axis = {
id: "salary",
min: 0,
title: {
text: "Number"
}
};
// Declare inital series with the values from the getSalaries function
var series = {
name: "2012",
data: Object.values(salary)
};
var series2 = {
name: "2013",
data: Object.values(salary2)
};
var series3 = {
name: "2014",
data: Object.values(salary3)
};
var series4 = {
name: "2015",
data: Object.values(salary4)
};
var series5 = {
name: "2016",
data: Object.values(salary5)
};
var myChart = Highcharts.chart("container", {
chart: {
type: "column"
},
title: {
text: "Test Data"
},
xAxis: {
categories: Object.keys(salary)
},
yAxis: axis,
series: [series, series2, series3, series4, series5]
});
// On draw, get updated salaries and refresh axis and series
table.on("draw", function() {
salary = getSalaries(table);
myChart.axes[0].categories = Object.keys(salary);
myChart.series[0].setData(Object.values(salary));
});
});
function getSalaries(table) {
var salaryCounts = {};
var salary = {};
}
function getRow(table, row) {
var chart = {};
var data = table.row(row).data();
for (i=1; i<data.length; i++) {
var x = $( table.column( i ).header() ).html();
var y = data[i].replace(/[^0-9.]/g, "") * 1;
chart[x] = y;
}
return chart;
}
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div id="container" style=" width: 100%; height: 400px;"></div>
<div class="container">
<table id="example_full2" class="display nowrap" width="100%"><thead>
<tr><th>Year</th><th>2012</th><th>2013</th><th>2014</th><th>2015</th><th>2016</th><th>2017</th><th>2018</th><th>2019</th><th>2020</th><th>2021</th></tr></thead>
<tr ><td> Data1</td><td>3,823</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data2</td><td>800</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data3</td><td>900</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data4</td><td>200</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data5</td><td>300</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data6</td><td>400</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
</tbody></table>
I'm using chart.js for showing statistics of reviews and messages of a user, but I'm getting problems with the scripts, now the stats are working but I got this error Cannot find element: #app and I don't know how to manage that.
If I use defer in this script (now I deleted it to see the stats working, but all the rest of the website don't)
<script src="{{ asset('js/app.js') }}"></script>
the stats doesn't work anymore and I get also another error like Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side effects in your templates, such as , as they will not be parsed.
So if I use defer i got errors, if I don't use defer it cannot find #app.
What should I do? Please help me, it's very important!
My app.blade.php file (where the script from before is)
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
{{-- <title>{{ config("app.name", "Bool n Roll") }}</title> --}}
<title>Bool 'n' Roll</title>
<script src="{{ asset('js/app.js') }}"></script>
<link rel="icon" href="{{asset('images/favicon.ico')}}" type="image/x-icon"/>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<nav class="navbar navbar-expand-md shadow-sm bg-nav fixed-nav">
<div class="container">
<a class="navbar-brand" href="{{ url('/') }}">
<img style="height: 50px;" src="{{ asset('images/logorock.png') }}" alt="">
</a>
<button class="navbar-toggler bg-dark" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<!-- Left Side Of Navbar -->
<ul class="navbar-nav mr-auto">
</ul>
<!-- Right Side Of Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Authentication Links -->
#guest
<li class="nav-item login-link rounded ml-2">
<a class="nav-link text-white px-2" href="{{ route('login') }}">{{ __('Login') }}</a>
</li>
#if (Route::has('register'))
<li class="nav-item register-link rounded ml-2">
<a class="nav-link title-orange px-2" href="{{ route('register') }}">{{ __('Sei un musicista? Registrati!') }}</a>
</li>
#endif
#else
<li class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle title-orange" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
{{ ucfirst(Auth::user()->name) }}
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="/admin">
Dashboard
</a>
<a class="dropdown-item" href="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('Logout') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
#csrf
</form>
</div>
</li>
#endguest
</ul>
</div>
</div>
</nav>
<main>
#yield('content')
</main>
<footer class="bg-dark text-white py-5">
<div class="container">
<div class="row text-center">
<div class="col-xs-12 col-md-4 col-lg-4">
<img style="height: 50px;" src="{{ asset('/images/footer-logo.png') }}" alt="">
<h5 class="my-3">Made with <span class="title-pink">♥</span> from Team 4</h5>
</div>
<div class="col-xs-12 col-md-4 col-lg-4">
<h5>Dev Team</h5>
<ul class="list-unstyled">
<li><a class="footer-list title-yellow" href="https://github.com/RobertoZeppilli">Roberto Zeppilli</a></li>
<li><a class="footer-list title-petrol" href="https://github.com/Edomak">Edoardo Maccherini</a></li>
<li><a class="footer-list title-orange" href="https://github.com/fabiopiro">Fabio Piroddi</a></li>
<li><a class="footer-list title-pink" href="https://github.com/michelafranchini">Michela Franchini</a></li>
</ul>
</div>
<div class="col-xs-12 col-md-4 col-lg-4">
<h5 class="my-3">Sei un musicista?</h5>
<ul class="list-unstyled">
<li class="nav-item register-link rounded">
<a class="nav-link title-orange" href="{{ route('register') }}">{{ __('Registrati subito!') }}</a>
</li>
</ul>
</div>
</div>
</div>
</footer>
</div>
#yield('script')
</body>
</html>
My stat view
Here I think I got major problems, maybe the script are not correct? Or there's a better way to place them inside the workflow?
#extends('layouts.app')
#section('content')
<div class="my_container">
<h1 class="stat_title">Le tue statistiche</h1>
#if (count($messages) == 0 && count($reviews) == 0)
<h2 id="empty_page">Non hai statistiche disponibili</h2>
#else
<div class="chart_1">
<h4>Numero di messaggi e recensioni ricevute ogni mese</h4>
<canvas id="myChart"></canvas>
</div>
<div class="chart_1">
<h4>Voti ricevuti ogni mese</h4>
<canvas id="myOtherChart"></canvas>
</div>
#endif
<p class="link_dashboard">Torna alla Dashboard</p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js" integrity="sha512-Wt1bJGtlnMtGP0dqNFH1xlkLBNpEodaiQ8ZN5JLA5wpc1sUlk/O5uuOMNgvzddzkpvZ9GLyYNa8w2s7rqiTk5Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.6/dayjs.min.js" integrity="sha512-bwD3VD/j6ypSSnyjuaURidZksoVx3L1RPvTkleC48SbHCZsemT3VKMD39KknPnH728LLXVMTisESIBOAb5/W0Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>dayjs().format()</script>
<script>
dayjs().format()
var ctx = document.getElementById('myChart');
var ct2 = document.getElementById('myOtherChart');
var commenti = {!! $reviews->toJson() !!};
var messaggi = {!! $messages->toJson() !!};
// console.log(commenti.length);
// console.log(messaggi.length);
var now = dayjs();
if (commenti[0]) {
var primaDataCommento = commenti[0].created_at;
var date1 = dayjs(primaDataCommento);
} else {
var date1 = now;
}
const primaDataMessaggio = messaggi[0].created_at;
const date2 = dayjs(primaDataMessaggio);
var datex;
if (date2 < date1) {
datex = date2;
} else {
datex = date1;
}
var diff = now.diff(datex, 'month');
var diffRece = now.diff(date1, 'month');
var months = [];
var monthsRece = [];
var recensioniMese = [];
var messaggiMese = [];
var voto1 = [];
var voto2 = [];
var voto3 = [];
var voto4 = [];
var voto5 = [];
// prima tabella
var x = 1;
let i = 0;
if (datex.$M == 0) {
diff++;
i++;
x--;
}
for (i; i <= diff; i++) {
var numeroMese = datex.$M + i + x;
months.push(numeroMese + '/2021');
var countRec = 0;
var countMes = 0;
for (let j = 0; j < commenti.length; j++) {
if (numeroMese == dayjs(commenti[j].added_on).$M + 1) {
countRec++;
}
}
for (let j = 0; j < messaggi.length; j++) {
if (numeroMese == dayjs(messaggi[j].added_on).$M + 1) {
countMes++;
}
}
recensioniMese.push(countRec);
messaggiMese.push(countMes);
}
// seconda tabella
x = 1;
i = 0;
if (date1.$M == 0) {
diffRece++;
i++;
x--;
}
for (i; i <= diff; i++) {
var numeroMeseRece = date1.$M + i + x;
monthsRece.push(numeroMeseRece + '/2021');
var countRece1 = 0;
var countRece2 = 0;
var countRece3 = 0;
var countRece4 = 0;
var countRece5 = 0;
for (let j = 0; j < commenti.length; j++) {
if (numeroMeseRece == dayjs(commenti[j].created_at).$M + 1) {
switch (commenti[j].vote) {
case 1:
countRece1++;
break;
case 2:
countRece2++;
break;
case 3:
countRece3++;
break;
case 4:
countRece4++;
break;
case 5:
countRece5++;
break;
default:
break;
}
}
}
voto1.push(countRece1);
voto2.push(countRece2);
voto3.push(countRece3);
voto4.push(countRece4);
voto5.push(countRece5);
}
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: months,
datasets: [
{
label: 'Numero di recensioni',
data: recensioniMese,
backgroundColor: [
'#0000ff8c',
],
borderColor: [
'#0000ff',
],
borderWidth: 1
},
{
label: 'Numero di messaggi ricevuti',
data: messaggiMese,
backgroundColor: [
'#ff00c88c',
],
borderColor: [
'#ff00c8',
],
borderWidth: 1
},
]
},
options: {
scales: {
y: {
beginAtZero: true,
ticks: {
stepSize: 1
}
}
}
}
});
var myChart = new Chart(ct2, {
type: 'bar',
data: {
labels: monthsRece,
datasets: [
{
label: 'Recensioni con voto 1',
data: voto1,
backgroundColor: [
'#ff00008c',
],
borderColor: [
'red',
],
borderWidth: 1
},
{
label: 'Recensioni con voto 2',
data: voto2,
backgroundColor: [
'#ffa6008c',
],
borderColor: [
'orange',
],
borderWidth: 1
},
{
label: 'Recensioni con voto 3',
data: voto3,
backgroundColor: [
'#ffff008c',
],
borderColor: [
'yellow',
],
borderWidth: 1
},
{
label: 'Recensioni con voto 4',
data: voto4,
backgroundColor: [
'#b7dd298c',
],
borderColor: [
'#b7dd29',
],
borderWidth: 1
},
{
label: 'Recensioni con voto 5',
data: voto5,
backgroundColor: [
'#57e32c8c',
],
borderColor: [
'#57e32c',
],
borderWidth: 1
},
]
},
options: {
scales: {
y: {
beginAtZero: true,
ticks: {
stepSize: 1
}
}
}
}
});
</script>
#endsection
The app.js file
Maybe the problem is here? I was trying to wrap the vue instance inside an addEventListener('load') or something to load the instance later, but it didn't work.
require('./bootstrap');
window.Vue = require('vue');
import router from './router';
var dayjs = require('dayjs')
// dayjs().format()
import Vue from 'vue';
import VueCarousel from 'vue-carousel';
Vue.use(VueCarousel);
// import Vue from "vue";
/**
* The following block of code may be used to automatically register your
* Vue components. It will recursively scan this directory for the Vue
* components and automatically register them with their "basename".
*
* Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
*/
// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
const app = new Vue({
el: '#app',
router,
dayjs,
});
The StatController
Everything is ok here, I'll leave it here just to show you the complete workflow of getting the statistics of reviews and messages of a user
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Musician;
use App\Message;
use App\Review;
use Illuminate\Support\Facades\Auth;
class StatController extends Controller
{
public function showStats(){
// prendo i dati del dottore registrato
$musician = Musician::where('user_id', Auth::id())->first();
// accedo alle tabelle dei messaggi e recensioni per prenderne i dati
$messages = Message::where('musician_id', $musician->id)->get();
$reviews = Review::where('musician_id', $musician->id)->get();
return view('admin.musicians.stats', compact('musician', 'messages', 'reviews'));
}
}
Update you app.blade.php. Remove this <script src="{{ asset('js/app.js') }}"></script> from header and put in body after footer.
...
<script src="{{ asset('js/app.js') }}"></script>
#yield('script')
</body>
</html>
Then use #stack('script') to load other script after app.js, update your My Stat View
#extends('layouts.app')
#section('content')
<div class="my_container">
<h1 class="stat_title">Le tue statistiche</h1>
#if (count($messages) == 0 && count($reviews) == 0)
<h2 id="empty_page">Non hai statistiche disponibili</h2>
#else
<div class="chart_1">
<h4>Numero di messaggi e recensioni ricevute ogni mese</h4>
<canvas id="myChart"></canvas>
</div>
<div class="chart_1">
<h4>Voti ricevuti ogni mese</h4>
<canvas id="myOtherChart"></canvas>
</div>
#endif
<p class="link_dashboard">Torna alla Dashboard</p>
</div>
#endsection
#push('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js" integrity="sha512-Wt1bJGtlnMtGP0dqNFH1xlkLBNpEodaiQ8ZN5JLA5wpc1sUlk/O5uuOMNgvzddzkpvZ9GLyYNa8w2s7rqiTk5Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.6/dayjs.min.js" integrity="sha512-bwD3VD/j6ypSSnyjuaURidZksoVx3L1RPvTkleC48SbHCZsemT3VKMD39KknPnH728LLXVMTisESIBOAb5/W0Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>dayjs().format()</script>
<script>
dayjs().format()
var ctx = document.getElementById('myChart');
var ct2 = document.getElementById('myOtherChart');
var commenti = {!! $reviews->toJson() !!};
var messaggi = {!! $messages->toJson() !!};
// console.log(commenti.length);
// console.log(messaggi.length);
var now = dayjs();
if (commenti[0]) {
var primaDataCommento = commenti[0].created_at;
var date1 = dayjs(primaDataCommento);
} else {
var date1 = now;
}
const primaDataMessaggio = messaggi[0].created_at;
const date2 = dayjs(primaDataMessaggio);
var datex;
if (date2 < date1) {
datex = date2;
} else {
datex = date1;
}
var diff = now.diff(datex, 'month');
var diffRece = now.diff(date1, 'month');
var months = [];
var monthsRece = [];
var recensioniMese = [];
var messaggiMese = [];
var voto1 = [];
var voto2 = [];
var voto3 = [];
var voto4 = [];
var voto5 = [];
// prima tabella
var x = 1;
let i = 0;
if (datex.$M == 0) {
diff++;
i++;
x--;
}
for (i; i <= diff; i++) {
var numeroMese = datex.$M + i + x;
months.push(numeroMese + '/2021');
var countRec = 0;
var countMes = 0;
for (let j = 0; j < commenti.length; j++) {
if (numeroMese == dayjs(commenti[j].added_on).$M + 1) {
countRec++;
}
}
for (let j = 0; j < messaggi.length; j++) {
if (numeroMese == dayjs(messaggi[j].added_on).$M + 1) {
countMes++;
}
}
recensioniMese.push(countRec);
messaggiMese.push(countMes);
}
// seconda tabella
x = 1;
i = 0;
if (date1.$M == 0) {
diffRece++;
i++;
x--;
}
for (i; i <= diff; i++) {
var numeroMeseRece = date1.$M + i + x;
monthsRece.push(numeroMeseRece + '/2021');
var countRece1 = 0;
var countRece2 = 0;
var countRece3 = 0;
var countRece4 = 0;
var countRece5 = 0;
for (let j = 0; j < commenti.length; j++) {
if (numeroMeseRece == dayjs(commenti[j].created_at).$M + 1) {
switch (commenti[j].vote) {
case 1:
countRece1++;
break;
case 2:
countRece2++;
break;
case 3:
countRece3++;
break;
case 4:
countRece4++;
break;
case 5:
countRece5++;
break;
default:
break;
}
}
}
voto1.push(countRece1);
voto2.push(countRece2);
voto3.push(countRece3);
voto4.push(countRece4);
voto5.push(countRece5);
}
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: months,
datasets: [
{
label: 'Numero di recensioni',
data: recensioniMese,
backgroundColor: [
'#0000ff8c',
],
borderColor: [
'#0000ff',
],
borderWidth: 1
},
{
label: 'Numero di messaggi ricevuti',
data: messaggiMese,
backgroundColor: [
'#ff00c88c',
],
borderColor: [
'#ff00c8',
],
borderWidth: 1
},
]
},
options: {
scales: {
y: {
beginAtZero: true,
ticks: {
stepSize: 1
}
}
}
}
});
var myChart = new Chart(ct2, {
type: 'bar',
data: {
labels: monthsRece,
datasets: [
{
label: 'Recensioni con voto 1',
data: voto1,
backgroundColor: [
'#ff00008c',
],
borderColor: [
'red',
],
borderWidth: 1
},
{
label: 'Recensioni con voto 2',
data: voto2,
backgroundColor: [
'#ffa6008c',
],
borderColor: [
'orange',
],
borderWidth: 1
},
{
label: 'Recensioni con voto 3',
data: voto3,
backgroundColor: [
'#ffff008c',
],
borderColor: [
'yellow',
],
borderWidth: 1
},
{
label: 'Recensioni con voto 4',
data: voto4,
backgroundColor: [
'#b7dd298c',
],
borderColor: [
'#b7dd29',
],
borderWidth: 1
},
{
label: 'Recensioni con voto 5',
data: voto5,
backgroundColor: [
'#57e32c8c',
],
borderColor: [
'#57e32c',
],
borderWidth: 1
},
]
},
options: {
scales: {
y: {
beginAtZero: true,
ticks: {
stepSize: 1
}
}
}
}
});
</script>
#endpush
I'm trying to create an app that takes latitude and longitude coordinates (along with other properties) from a json file and apply them to my map, along with filter and search options. I was following along with this tutorial: http://zevross.com/blog/2014/05/27/synchronize-leaflet-map-data-with-angularjs/
I can't figure out if my json file is not formatted correctly or if I'm not iterating over the file right in my javascript. Thanks for any help on this.
controllers.js
'use strict';
myApp.controller('DemoController', ["$scope", "$http", '$q', '$filter',
function($scope, $http, $q, $filter) {
$scope.search = {
customer: '',
year: ''
}
$scope.tableClick = function(dat){
$scope.search.customer = dat.customer
}
// function countryClick(country, event) {
// console.log(country);
// }
$scope.orderByField = 'year';
$scope.$on("leafletDirectiveMap.geojsonMouseover", function(ev,
leafletEvent) {
customerMouseover(leafletEvent);
});
$scope.$on("leafletDirectiveMap.geojsonClick", function(ev,
featureSelected, leafletEvent) {
$scope.search.customer=featureSelected.properties.customer
});
$scope.clearSelections = function(){
$scope.search.customer = ''
$scope.search.year = ''
}
$scope.$watchCollection("search",
function(newValue, oldValue) {
if (newValue === oldValue) {
return;
}
var data = angular.copy($scope.acct_year);
var justGroup = _.filter(data.features, function(x) {
if (newValue.year == '' || newValue.year == undefined) {
if (!newValue.customer) {
return true
} else {
return $filter('filter')([x.properties.customer],
newValue.customer).length > 0
}
} else {
if (!newValue.customer) {
return x.properties.year == newValue.year
} else {
return x.properties.year == newValue.year & $filter('filter')([x.properties.customer], newValue.customer).length > 0
}
}
})
data.features = justGroup
$scope.geojson = {
data: data,
style: style,
resetStyleOnMouseout: true
}
}
);
angular.extend($scope, {
center: {
lat: 40.8471,
lng: 14.0625,
zoom: 2
},
scrollWheelZoom: false,
legend: {
colors: ['#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f'],
labels: ['2010', '2011', '2012', '2013', '2014', '2015']
}
});
var opac = 0.8
var circlecolors = {
'2010': {
color: '#7fc97f',
opacity: opac
},
'2011': {
color: '#beaed4',
opacity: opac
},
'2012': {
color: '#fdc086',
opacity: opac
},
'2013': {
color: '#ffff99',
opacity: opac
},
'2014': {
color: '#386cb0',
opacity: opac
},
'2015': {
color: '#f0027f',
opacity: opac
}
}
function getColorFootball(d) {
return circlecolors[d.year] || {
color: 'grey',
opacity: 0
}
}
function style(feature) {
var vals = getColorFootball($scope.footballObject[feature.properties.ISO3])
var rads = getRadiusFootball($scope.footballObject[feature.properties.ISO3])
return {
fillColor: vals.color,
radius: rads,
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: vals.opacity
};
}
function getRadiusFootball(d) {
if (d) {
d = d['year']
return Math.sqrt(1500 / d)
} else {
return 0
}
}
$scope.acct_year= [];
$http.get('acct_year_small.json').success(function(data, status) {
var tempAcct_Json = {};
for (var i = 0; i < data.length; i++) {
var customer = data[i];
tempAcct_Json[customer['CUSTOMER']] = customer;
//then set on scope
$scope.footballObject = tempAcct_Json;
$scope.acct_year = data;
}
});
// http://thematicmapping.org/downloads/world_borders.php
// qgis to do centroids, move US, save as geojson
$scope.acct_yeargeo = {};
$http.get("world.geojson").success(function(data, status) {
//data.features = data.sort(propSort(["PARK_NAME"]));
var featuresLim = []
var minrank = 0
for (var i = 0; i < data.features.length; i++) {
var amatch = _.where($scope.acct_year, {
"alpha-3": data.features[i].properties['ISO3']
})
if (amatch.length > 0) {
var feat = data.features[i]
var currank = amatch[0]['year']
var curgroup = amatch[0]['year']
var curcountry = amatch[0]['customer']
feat.properties['year'] = currank
feat.properties['year'] = curgroup
feat.properties['customer'] = curcountry
featuresLim.push(feat)
} //end if
} //end loop through features
featuresLim.sort(propSort("year"));
//featuresLim.sort(sortBy)
data.features = featuresLim
$scope.acct_yeargeo = data
angular.extend($scope, {
geojson: {
data: data,
style: style,
resetStyleOnMouseout: true
}
}); //end extend
}); //end get features
function countryMouseover(leafletEvent) {
var layer = leafletEvent.target;
layer.setStyle({
weight: 2,
color: '#666',
fillColor: 'white'
});
//layer.bringToFront();
}
function propSort(props) {
return function sort(a, b) {
var p;
a = a.properties;
b = b.properties;
p = props;
if (a[p] < b[p]) return -1;
if (a[p] > b[p]) return 1;
};
}
}
]);
//mapoptions
myApp.controller("GoogleMapsController", ["$scope",
function($scope) {
angular.extend($scope, {
world: {
lat: 39.809860,
lng: -98.555183,
zoom: 4
},
scrollwheel: false,
layers: {
baselayers: {
googleTerrain: {
name: 'Google Terrain',
layerType: 'TERRAIN',
type: 'google'
}
}
},
defaults: {
scrollwheel: false
}
});
}
]);
test2.html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>Map</title>
<link href="../css/bootstrap.min.css" rel="stylesheet" />
<link href="../css/leaflet.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css"
href="http://cloud.github.com/downloads/lafeber/world-flags-
sprite/flags32.css" />
<script src="http://maps.google.com/maps/api/js?v=3.2&sensor=false">
</script>
<script
src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-
min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"
rel="stylesheet">
<link rel="stylesheet" href="../css/app.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.js"></script>
</head>
<body ng-controller="DemoController">
<div class="container">
<div class="row">
<h1>Map</h1>
</div>
<div class="row">
<div ng-controller='GoogleMapsController'>
<!-- <leaflet center="center" events="events" legend="legend"
geojson="geojson" width='100%' height='600'></leaflet> -->
<leaflet center="world" events="events" legend="legend"
width='100%' height='400' layers='layers' geojson="geojson"></leaflet>
</div>
<div class="info country f32">
<div ng-show="geojson.selected" class="flag" ng-
class="geojson.selected.properties.ISO2|lowercase"></div>
<span class='countryselected' ng-cloak>{{
geojson.selected.properties.NAME ?
geojson.selected.properties.NAME + ' — Years ' +
footballObject[geojson.selected.properties.ISO3].year : 'Select
customer on map'}}</span>
</div>
<!-- <div class="info box">Map center: [ lat: {{ center.lat |
number:4 }}, lng: {{ center.lng | number:4 }} ]</div> -->
<div class="col-md-10 col-md-offset-1">
<div class="row well filtering">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="search" class="col-sm-6 control-
label">Filter by Customer</label>
<input ng-model="search.country">
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Filter by
Year</label>
<select class="selectpicker" ng-model='search.Group'
ng-options="city.Group as city.Group for city in acct_year | unique:'year'
| orderBy:'year'" fix>
<option value="" selected="selected">-- All Years --</option>
</select>
</div>
<div class="form-group">
<button type="button" class="btn btn-grey col-sm-2 col-sm-
offset-5" ng-click='clearSelections()'>Clear
Selections</button>
</div>
</form>
</div>
<div class="row">
<table ng-cloak class='table table-striped full'>
<thead>
<tr class="foot">
<th><a href="" ng-click="orderByField =
'customer'; reverse=!reverse">Customer</a>
</th>
<th><a href="" ng-click="orderByField =
'cust_code'; reverse=!reverse">Customer Code</a>
</th>
<th><a href="" ng-click="orderByField = 'grand
total'; reverse=!reverse">Grand Total</a>
</th>
<th><a href="" ng-click="orderByField = 'year';
reverse=!reverse">Year</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="foot in acct_year |
orderBy:orderByField:reverse | filter:search" ng-
click="tableClick(foot)">
<td class='country'>{{foot.customer}}</td>
<td>{{foot.cust_code}}</td>
<td>{{foot.grand_total}}</td>
<td>{{foot.year}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<hr>
<footer>
</footer>
</div>
</body>
<script>
</script>
<script src="../js/angular.min.js"></script>
<script src="../js/angular-route.js"></script>
<script src="../js/angular-leaflet-directive.js"></script>
<script src="../js/app.js"></script>
<script src="../js/controllers.js"></script>
<script src="../js/directives.js"></script>
<script src="../js/filters.js"></script>
<script src="../js/Google.js"></script>
</body>
acct_year_small.json (just a testing file, actual file has much more data)
features =
[
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ -102.852,30.877528 ]
},
"properties": {
"CUSTOMER":"Bridgestone Americas Tire Operations",
"CUST_CODE":20,
"GRAND TOTAL":"$11,311.82",
"YEAR":2010
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ -76.41533,39.337798 ]
},
"properties": {
"CUSTOMER":"D & M Equipment",
"CUST_CODE":47,
"GRAND TOTAL":"$4,500.00",
"YEAR":2010
}
}
];
If your JSON file is correct, you need to change
tempAcct_Json[customer['CUSTOMER']] = customer;
to
tempAcct_Json[customer.properties['CUSTOMER']] = customer;
I have uploaded a page where the error occurs. It´s displayed in the console (please use F12 in Firefox or Chrome Browser).
http://preventdefault.lima-city.de/index.php
This line is wrong: "kendo.stringify(grid.getOptions())"
My Question: How must i change this code so that i could store the changed table settings?
I also insert the html code here, Thx for answer !
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.default.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1411/js/jszip.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1411/js/kendo.all.min.js"></script>
<style type="text/css">
.button-center {
text-align: center; /* button position in grid */
}
</style>
</head>
<body role="document">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active">one</li>
<li>two</li>
</ul>
</div>
</div>
</nav>
<div class="container theme-showcase" id="main" role="main">
<div class="container">
<h1>Page<small> one</small></h1>
</div>
<div class="row-fluid">
<div id="grid_one"></div>
</div> <!-- row -->
<div class="row-fluid">
<div id="log"></div>
</div> <!-- row -->
</div> <!-- container -->
<script>
<!-- --------------------------------------------------------------------------------- -->
var firstNames = ["Nancy", "Andrew", "Janet", "Margaret", "Steven",
"Michael", "Robert", "Laura", "Anne", "Nige"],
lastNames = ["Davolio", "Fuller", "Leverling", "Peacock", "Buchanan",
"Suyama", "King", "Callahan", "Dodsworth", "White"],
cities = ["Seattle", "Tacoma", "Kirkland", "Redmond", "London",
"Philadelphia", "New York", "Seattle", "London", "Boston"],
titles = ["Accountant", "Vice President, Sales", "Sales Representative",
"Technical Support", "Sales Manager", "Web Designer",
"Software Developer", "Inside Sales Coordinator", "Chief Techical Officer",
"Chief Execute Officer"],
birthDates = [new Date("1948/12/08"), new Date("1952/02/19"), new Date("1963/08/30"),
new Date("1937/09/19"), new Date("1955/03/04"), new Date("1963/07/02"),
new Date("1960/05/29"), new Date("1958/01/09"), new Date("1966/01/27"),
new Date("1966/03/27")];
function createRandomData(count) {
var data = [], now = new Date();
for (var i = 0; i < count; i++) {
var firstName = firstNames[Math.floor(Math.random() * firstNames.length)],
lastName = lastNames[Math.floor(Math.random() * lastNames.length)],
city = cities[Math.floor(Math.random() * cities.length)],
title = titles[Math.floor(Math.random() * titles.length)],
birthDate = birthDates[Math.floor(Math.random() * birthDates.length)],
age = now.getFullYear() - birthDate.getFullYear();
data.push({
Id: i + 1,
FirstName: firstName,
LastName: lastName,
City: city,
Title: title,
BirthDate: birthDate,
Age: age
});
}
return data;
}
<!-- --------------------------------------------------------------------------------- -->
function onChangeSelection() {
var selectedItem = this.dataItem(this.select());
var Text = '<h1><small>row name=</small>' + selectedItem.FirstName + " " + selectedItem.LastName + "</h1>";
console.log(Text);
$("#log").html(Text);
$("#ordernumber").val(selectedItem.ordernumber);
}
<!-- --------------------------------------------------------------------------------- -->
function startbuttonclick(e) {
var data = this.dataItem($(e.currentTarget).closest("tr"));
var Text = "<h1><small>Button click name=</small> " + data.FirstName + " " + data.LastName + "</h1>";
console.log(Text);
$("#log").html(Text);
e.preventDefault();
}
<!-- --------------------------------------------------------------------------------- -->
$(document).ready(function() {
$("#grid_one").kendoGrid({
dataSource: {
data: createRandomData(10),
schema: {
model: {
fields: {
FirstName: { type: "string" },
LastName: { type: "string" },
City: { type: "string" },
Title: { type: "string" },
BirthDate: { type: "date" },
Age: { type: "number" }
}
}
},
pageSize: 10
},
height: 500,
dataBound: saveState,
columnResize: saveState,
columnShow: saveState,
columnHide: saveState,
columnReorder: saveState,
columnLock: saveState,
columnUnlock: saveState,
selectable: true,
resizable: true,
columnMenu: true,
scrollable: true,
sortable: true,
filterable: true,
change: onChangeSelection,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5,
pageSizes: [5, 10, 20, 250]
},
columns: [
{
field: "FirstName",
title: "First Name",
width: "150px",
},
{
field: "LastName",
title: "Last Name",
width: "150px",
},
{
field: "City",
hidden: true
},
{
field: "Title",
hidden: true
},
{
field: "BirthDate",
title: "Birth Date",
template: '#= kendo.toString(BirthDate,"MM/dd/yyyy") #',
width: "175px",
},
{
field: "Age",
width: "150px",
},
{
command: {
text: "Start",
click: startbuttonclick },
title: "Start",
width: "65px",
attributes:{
"class":"button-center"}
}
]
});
<!-- ------------------------------------------------------------------------------ -->
var grid = $("#grid_one").data("kendoGrid");
function saveState(e) {
e.preventDefault();
localStorage["kendo-grid-one"] = kendo.stringify(grid.getOptions());
};
$(function (e) {
var options = localStorage["kendo-grid-one"];
if (options) {
grid.setOptions(JSON.parse(options));
} else {
grid.dataSource.read();
}
});
});
<!-- --------------------------------------------------------------------------------- -->
</script>
</body>
</html>
Edited for:
Your var grid = $("#grid_one").data("kendoGrid"); only defined once, and it may not have data upon defined, it maybe insert by your kendogrid after.
Domready Part should also need to have reference to it, you can either put it at origin location or move it into the function
From your and dfsq's replies, the problem is that json CANNOT store a function, so you have to add it back to when retrieved from the localstorage
In your current code, saveState will always be called before the setOptions one, which means the saveState just erased by your saveState function, so you have to move the setoptions code forward.
Changes a lot
$(document).ready(function() {
// Get options first
var options = localStorage["kendo-grid-one"];
if (options) {
options = JSON.parse(options);
// Workaround to addback event
options.columns[6].command.click = startbuttonclick;
}
$("#grid_one").kendoGrid({
dataSource: {
data: createRandomData(10),
schema: {
.....
});
if (options) {
$("#grid_one").data("kendoGrid").setOptions(options);
}
<!-- ------------------------------------------------------------------------------ -->
function saveState(e) {
var grid = $("#grid_one").data("kendoGrid");
e.preventDefault();
localStorage["kendo-grid-one"] = kendo.stringify(grid.getOptions());
};
See Demo Here, now it works.
saveState part use dfsq's may be better
options.columns[6].command.click = startbuttonclick; may be can write in a more elegant style, but here I just want to show why the issues come out and how to apply a basic solution.
I don't know kendo but the issue must be that the saveState function is called before the grid is declared.
JSFiddle: http://jsfiddle.net/8x7v7mga/1/
So somewhere in the construction of the kendo object, one of the saveState handlers is called.
You can avoid this by declaring the grid variable first and then in the saveState simply check if grid is defined or not:
var grid = null;
$("#grid_one").kendoGrid({ ... });
grid = $("#grid_one").data("kendoGrid");
function saveState(e) {
e.preventDefault();
grid && localStorage["kendo-grid-one"] = kendo.stringify(grid.getOptions());
};
The problem is that saveState function is called before grid is initialzed. you cantually don't need grid reference since saveState s called in grid context so you can simply use this instead:
function saveState(e) {
e.preventDefault();
localStorage["kendo-grid-one"] = kendo.stringify(this.getOptions());
};
I am struggling to see where I am getting an error of 'rowdata is undefined'? when I run my script and press the delete button. I am using jqxwidgets grid:
http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/index.htm
If someone could help out new user or how I can troubleshoot in firebug 1.9, I would be grateful. I have included my code for your inspection. Thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.classic.css" type="text/css" />
<script type="text/javascript" src="../../scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqx-all.js"></script>
<script type="text/javascript" src="../../scripts/gettheme.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdatetimeinput.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcalendar.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxtooltip.js"></script>
<script type="text/javascript" src="../../jqwidgets/globalization/jquery.global.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// prepare the data
var source =
{
datatype: "json",
datafields: [
{ name: 'id'},
{ name: 'type'},
{ name: 'service'},
{ name: 'quantity'},
{ name: 'department'},
{ name: 'date', type: 'date', format: 'yyyy-MM-dd HH:mm:ss'},
],
url: 'data.php',
updaterow: function (rowid, rowdata) {
// synchronize with the server - send update command
var data = "update=true&type=" + rowdata.type + "&service=" + rowdata.service + "&quantity=" + rowdata.quantity;
data = data + "&department=" + rowdata.department + "&date=" + rowdata.date;
data = data + "&id=" + rowdata.id;
$.ajax({
dataType: 'json',
url: 'data.php',
data: data,
success: function (data, status, xhr) {
// update command is executed.
//alert(rowdata);
}
});
},
deleterow: function (rowid, rowdata) {
// synchronize with the server - send update command
var data = "delete=true&type=" + rowdata.type + "&service=" + rowdata.service + "&quantity=" + rowdata.quantity;
data = data + "&department=" + rowdata.department + "&date=" + rowdata.date;
data = data + "&id=" + rowdata.id;
$.ajax({
dataType: 'json',
url: 'data.php',
data: data,
success: function (data, status, xhr) {
// update command is executed.
//alert(rowid);
console.log(rowid);
}
});
}
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
source: source,
theme: 'classic',
width: 900,
altrows: true,
pageable: true,
sortable: true,
filterable: true,
autoheight: true,
pagesizeoptions: ['10', '20', '30', '40'],
editable: true,
ready: function () {
var button = $("<input type='button' value='Add' id='myButton'/>");
button.jqxButton({ height: 20 });
button.click(function () {
$("#jqxgrid").jqxGrid('addrow', null, []);
});
$(".jqx-grid-pager > div:first").append(button);
},
ready: function () {
//var value = $('#jqxrid').jqxGrid('deleterow', rowid);
var delbutton = $("<input type='button' value='Delete' id='DelButton'/>");
delbutton.jqxButton({ height: 20 });
delbutton.click(function () {
$('#jqxgrid').jqxGrid('deleterow', id);
});
$(".jqx-grid-pager > div:first").append(delbutton);
},
columns: [
{ text: 'id', editable: false, datafield: 'id', width: 100 },
{ text: 'Type', datafield: 'type', width: 150},
{ text: 'Service', datafield: 'service', width: 150 },
{ text: 'Quantity', datafield: 'quantity', width: 180 },
{ text: 'Department', datafield: 'department', width: 90 },
{ text: 'Date', datafield: 'date', columntype: 'datetimeinput', cellsformat: 'dd/MM/yyyy HH:mm:ss', width: 230, showCalendarButton: false }
]
});
});
</script>
</head>
<body class='default'>
<div id='content'>
<script type="text/javascript">
$(document).ready(function () {
var theme = 'classic';
// Create a jqxDateTimeInput
$("#jqxWidget").jqxDateTimeInput({ width: '250px', height: '25px', theme: theme, formatString: 'dd/MM/yyyy HH:mm:ss' });
});
</script>
<div id='jqxWidget'>
</div>
</div>
<div id="jqxgrid"></div>
</body>
</html>
You are invoking deleterow() without the proper parameters :)
Signature:
deleterow: function (rowid, rowdata) {}
Invocation:
delbutton.click(function () {
$('#jqxgrid').jqxGrid('deleterow', id /* Missing argument */ );
});
You should add the rowdata as an argument. I don't think this code is to be considered very safe.. (which could be rewritten anyways, skipping the "data = data +", see below ).
var data = "delete=true&type=" + rowdata.type + "&service=" + rowdata.service + "&quantity=" + rowdata.quantity;
data = data + "&department=" + rowdata.department + "&date=" + rowdata.date;
data = data + "&id=" + rowdata.id;
You can obtain the rows as follows (
You should ask for a confirmation, first! ):
delbutton.click(function () {
var rows = $('#grid').jqxGrid('getrows'),
selectedRowIndex = $('#grid').jqxGrid('getselectedrowindex'),
selectedRow = rows[ selectedRowIndex ];
if( confirm("Are you sure you wish to delete the row with index '" + selectedRowIndex + "'?") {
$('#jqxgrid').jqxGrid('deleterow', selectedRowIndex, selectedRow );
}
});
This would be more readable and usable:
var data = [
"delete=", "true",
"&type=", rowdata.type,
"&service=", rowdata.service,
"&quantity=", rowdata.quantity,
"&department=", rowdata.department,
"&date=", rowdata.date,
"&id=", rowdata.id
].join("");
Actually I think the following might make it more complex and less errorprone, but easier to use:
// Another solution
var customDataProperties = {
"delete": "true"
// ,"another": 2
}
var rowdataProperties = [
"type",
"service",
"quantity",
"department",
"date",
"id"
];
function getData( rowdataObject ) {
// Add additional
var data = [];
function createParameterSetString( property, value ) {
return [ "&", property, "=", value ].join("");
}
for( var propertyName in customDataProperties ) {
data.push( createParameterSetString( propertyName, customDataProperties[ propertyName ] ) );
}
for( var i = 0, ln = rowdataProperties.length; i < ln; i++ ) {
var property = rowdataProperties[i];
data.push( createParameterSetString( property, rowdataObject[ property ] ) );
}
if( data.length != 0 ) { data.pop( 0 ); }
return data.join("");
}
As you can see, you can easily extend parameters this way.