I am using Laravel 5.5 and I am trying to work with ag-grid and want to load my data that is coming from my db directly into the Javascript file.
My Migration looks like the following:
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
My Frontend looks like the following:
example.js
// specify the columns
var columnDefs = [
{headerName: "Name", field: "name"},
{headerName: "Created_At", field: "created_at"},
{headerName: "Updated_At", field: "updated_at"}
];
// specify the data
var rowData = [
{name: "TODO 1", created_at: "01.01.2018", updated_at: "05.11.2016"},
{name: "TODO 1", created_at: "01.01.2018", updated_at: "05.11.2016"} // here I would like to replace this dummy data with my db data
];
// let the grid know which columns and what data to use
var gridOptions = {
columnDefs: columnDefs,
rowData: rowData,
onGridReady: function () {
gridOptions.api.sizeColumnsToFit();
}
};
// used in our jasmine test
function selectAllRows() {
gridOptions.api.selectAll();
}
// wait for the document to be loaded, otherwise ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function () {
// lookup the container we want the Grid to use
var eGridDiv = document.querySelector('#myGrid');
// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(eGridDiv, gridOptions);
});
home.blade.php
<html>
<head>
<script src="https://www.ag-grid.com/dist/ag-grid/ag-grid.js"></script>
<script src="example.js"></script>
</head>
<body>
<h1>Ag-Grid Example</h1>
<div id="myGrid" style="height: 115px;width:500px" class="ag-fresh"></div>
<!-- Own Scripts -->
<script src="{{ asset('js/example.js') }}"></script>
</body>
</html>
Any suggestions how to insert my data that I load from the database into the the variable rowData in my example.js file?
I appreciate your replies!
If you're getting the data as a collection, you can just pass the data like this:
<script>
var app = {{ $collection }};
</script>
If it's an array, you can use #json directive:
<script>
var app = #json($array);
</script>
You also could use one of the available packages or put the data into a hidden input HTML element to be able to use this data in JS.
Related
I'm currently working on a project with Meteor. It is used to create, edit, delete and vote for polls. Now I'd like to have a page where you can see the results of the answers shown with "ChartJS".
I got following code:
Templates:
<template name="pollAnalysis">
<h3>Auswertung {{title}}</h3>
{{#each questions}}
{{> questionAnalysis}}
{{/each}}
</template>
<template name="questionAnalysis">
<div class="post">
<div class="post-content">
<h3>{{question}}</h3>
{{> analysisChart}}
</div>
</div>
</template>
<template name="analysisChart">
<canvas id="{{_id}}" class="mychart" height="400" width="400"></canvas>
</template>
Helpers:
Template.pollAnalysis.helpers({
questions: function(){
return Questions.find({pollId: this._id});
}
});
First I had the problem that the chartjs didn't get display, I fixed it by doing this (just for a single ID, thats where I get stuck)
Template.analysisChart.rendered = function(){
drawChart();
}
function drawChart(){
var data = [
{
value: 10,
color:"#27AE60",
highlight: "#2ECC71",
label: "trifft zu"
},
{
value: 10,
color: "#16A085",
highlight: "#1ABC9C",
label: "trifft eher zu"
}
]
var ctx = $("#Cb8CdtDpdKA9y4Hij").get(0).getContext("2d");
var myNewChart = new Chart(ctx);
new Chart(ctx).Pie(data);
}
Now I need the drawChart dynamically.
pseudo code:
function drawChart(questionId){
var data = [
{
value: Questions_Users.find({questionId: questionId}, answer: "yes").count(),
color:"#27AE60",
highlight: "#2ECC71",
label: "trifft zu"
},
{
value: Questions_Users.find({questionId: questionId}, answer: "no").count(),
color: "#16A085",
highlight: "#1ABC9C",
label: "trifft eher zu"
}
]
var ctx = $("#"+questionId).get(0).getContext("2d");
var myNewChart = new Chart(ctx);
new Chart(ctx).Pie(data);
}
So I have to give over the questionId from the Template.analysisChart.rendered to the drawChart() function. But how can I get the questionId ("{{_id}}" in analysisChart template) of the current element in the Template.analysisChart.rendered function?
Greetings & happy programming
faebuk
A quick answer would be to use something like
Template.analysisChart.rendered = function(){
Tracker.autorun(function(){
var data = Questions_Users.find();
drawChart();
})
}
Or look into observeChanges, something like:
Template.analysisChart.rendered = function(){
Questions_Users.find().observeChanges({
added:function(id, fields){
//update Chart.datasets
Chart.update()
}
})
}
I have an example project that just implements the update logic with Tracker and an ReactiveArray (tracker is part of Meteor's front-end, ReactiveArray is similar to Minimongo with fetch): https://github.com/Slava/jsconf-asia-demo/blob/master/tracker.html#L47-L61
To adapt it to a Meteor app, you would start an autorun in template's rendered callback and depend on the minimongo query that you fetch and feed to Chart.js. Once you done, tell Chart.js to update itself.
I am new to django.
From my findings, I tried this way, but didn't work.
<script type="text/javascript" >
var data = {{json}}
</script>
I am trying to use data table from this website, http://www.datatables.net/manual/data.
<script type="text/javascript" class="init">
var temp = '{{campaignList|escapejs}}'; // should be a list, but becomes a string
alert(typeof temp)
$(document).ready( function () {
$('#campaigns').DataTable({
data: temp,
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'date' },
]
});
} );
</script>
When I check the type before passing into datatable, the type becomes string.
I also tried {{campaignList|escapejs}} without quote, but didn't work.
Any suggestion? Thanks.
If campaignList is a json string, pass it to safe filter to prevent escape:
var data = {{ campaignList|safe }};
I am posting a form to a url from a page that displays backbonejs models.
This is how my backbonejs model looks like in the form:
Form:
<form class="form-horizontal" action="profit" method="post">
<fieldset>
<!-- Form Name -->
<legend>Form Name</legend>
<!-- Button -->
<div class="control-group">
<div class="controls">
<div id="example-1-result" class="backgrid-container"></div>
<button id="profit" name="profit" class="btn btn-primary">Button</button>
</div>
</div>
</fieldset>
</form>
JavaScript:
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="../static/js/bootstrap.min.js"></script>
<script>
var Trade = Backbone.Model.extend({});
var Trades = Backbone.Collection.extend({
model: Trade,
url: "fodata"
});
var columns = [
{
name: "trade_id",
label: "Trade Id",
// The cell type can be a reference of a Backgrid.Cell subclass, any Backgrid.Cell subclass instances like *id* above, or a string
cell: "string" // This is converted to "StringCell" and a corresponding class in the Backgrid package namespace is looked up
},
{
name: "order_id",
label: "Order Id",
// The cell type can be a reference of a Backgrid.Cell subclass, any Backgrid.Cell subclass instances like *id* above, or a string
cell: "string" // This is converted to "StringCell" and a corresponding class in the Backgrid package namespace is looked up
},
{
name: "trade_date",
label: "Trade Date",
cell: "datetime",
},
{
name: "trade_time",
label: "Trade Time",
cell: "datetime",
},
{
name: "contract_description",
label: "Contract Description",
cell: "string" // An integer cell is a number cell that displays humanized integers
},
{
name: "expiry_date",
label: "Expiry Date",
cell: "datetime",
},
{
name: "buy_quantity",
label: "Buy Quantity",
cell: "integer" // An integer cell is a number cell that displays humanized integers
}, {
name: "buy_rate",
label: "Buy Rate",
cell: "number",
},
{
name: "sale_quantity",
label: "Sale Quantity",
cell: "integer" // An integer cell is a number cell that displays humanized integers
}, {
name: "sale_rate",
label: "Sale Rate",
cell: "number",
}
];
var trades = new Trades;
var grid = new Backgrid.Grid({
columns: columns,
collection: trades
});
// Initialize a new Grid instance
var refreshgrid = function(){
$("#example-1-result").prepend(grid.render().$el);
}
</script>
Now, while submitting, I need to submit the trades JSON data but I'm not able to get the model to submit.
How do I achieve this? Do I need to use backbonejs forms?
Backgrid is supposed to give you something to quickly edit all the models you give it to it (through the collection) using the normal backbone mechanisms. So technically, you shouldn't use a form to wrap it, and when editing each Trade model, the Trade model should be saved() after the end of the edit. Backgrid is a nice way to wrap basic CRUD on top of a resource.
If that's not the behavior you want, then maybe Backgrid isn't what you need?
That being said, nothing prevents you at anytime, no matter what's in the form, to do something like:
$("form").on("submit", function(event){
//Don't send the form, stay on the page
event.preventDefault();
//Transform the collection of Trades into an array of JSONified Trade
data = trades.map(function(trade){
return trade.toJSON();
});
//Post this to the server
$.post("url", {trades: data}, ... );
return false;
});
But that seems odd.
If I misunderstood, maybe you can clarify your intent a bit? Hope this helps!
You should just be able to serialize the model and POST it.
See: http://api.jquery.com/serialize/
If you .serialize the data you want and send that as part of your POST request it should work. Alternatively if you're looking for something a bit more advanced take a look at syphon:
http://lostechies.com/derickbailey/2012/05/17/backbone-syphon-serialize-form-inputs-to-javascript-objects/
Serializing is most likely the key to what you want to achieve.
I want to display a set of data which i am retrieving by an asynchronous call to the server using dojo.xhrget() method. I am retrieving data through a URL and i want that everytime a user clicks in content pane a new set of values gets displayed in grid without refreshing whole page. The problem is that data is not getting displayed in Grid. I am receiving an error by xhrget() error method.
The code for my script is ::
<script>
function populateGrid(){
dojo.xhrGet({
url: "http://localhost:8080/2_8_2012/jsp/GetJson.jsp",
load: fillGrid,
error:handleError,
preventCache:true
});
}
function fillGrid(data, ioArgs)
{
alert(data);
var newData = {
identifier: "ID",
items: data
};
var dataStore = new dojo.data.ItemFileReadStore({data: newData, id:"dataStoreId"});
var gridStructure =[[
{ field: "ID",
name: "ID_Emp",
width: "20%",
classes:"firstName"
},
{
field: "Names",
name: "Name",
width: "20%",
classes: "firstName"
},
{ field: "Email",
name: "Mail",
width: "20%",
classes:"firstName"
}
]
];
var grid = dijit.byId("grid.DataGrid");
grid.setStore(dataStore);
grid.startup();
}
function handleError() {
alert("An error occurred while invoking the service.");
}
</script>
Now , here the output of alert(data) and http://localhost:8080/2_8_2012/jsp/GetJson.jsp is same i.e ::
[{"ID":1,"Names":"Shantanu","Email":"shantanu.tomar#gmail.com"},{"ID":2,"Names":"Mayur","Email":"mayur.sharma#gmail.com"},{"ID":26,"Names":"Rohit"}]
My xhr.get function is working fine in terms of data retrieval. i.e when i update the values in a database. I do get the alert(data) output with that updated value without refreshing the whole page again. But data is not displayed in Data grid.
I am receiving an alert
An error occurred while invoking the service.
The code for http://localhost:8080/2_8_2012/jsp/GetJson.jsp is ::
<%# page language="java" contentType="application/json; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="MyPackage.PopulateTextbox" %>
<%
String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
%>
<%=temp1 %>
The markup code is ::
<div id="grid.DataGrid" data-dojo-type="dojox.grid.DataGrid" title="Simple Grid" data-dojo-props= "autoWidth:true, structure: gridStructure" style="width:900px; height:200px;"></div>
<div id="contentpaneid" dojoType="dijit.layout.ContentPane" title="Pending Activities" style="background-image: url('http://localhost:8080/2_8_2012/images/17.png');" onclick="populateGrid">
I am not getting what's the problem. Can u please help me out on why am i getting an error alert. thanks.
Pratik Chandra rightly alluded to the issue - the datagrid is being populated without any store being set. I suggest changing your datagrid to be populated programmatically
So your declaration:
<div id="grid.DataGrid" data-dojo-type="dojox.grid.DataGrid"
neeeds to be changed to:
<div id="mygrid" ></div>
and then change the line:
var grid = dijit.byId("grid.DataGrid");
to:
var grid = new dojox.grid.DataGrid({
id: "grid",
jsid: "grid",
store: dataStore,
structure: gridStructure,
style: 'width:900px;height:300px;'
}, dojo.byId("mygrid"));
grid.startup();
Also note that whenever you want to refresh the data in the grid, you do not need to repopulate the grid, you can just update the datastore with new values and the datagrid will automatically refresh with new data :-) Dojo takes care of that part.
To clean existing data in the datastore and populate it with new data, set the clearOnClose property on your IFRS. See: Updating Dojo Dijit FilteringSelect's store with asynchonous data to learn about clearOnClose
I have this problem
I'm using DataGrid + dojo.store.JsonRest as store. I want to load only those items that are currenlty neccesary. So when I have 10000 items only ~ 100 is loaded initialy and the rest is downloaded as the user scrolls the grid.
I created two files
datagridtest.php contains datagrid
jsonsource.php implements test datasource (that should return no more that 499 records)
First 25 items is displayed fine. But when I try to scroll down datagrid dosn't request new items - checked it with FireBug.
Please help. What Am i doing wrong.
Below is my code:
datagridtest.php:
<html><head>
<link rel="stylesheet" type="text/css" href="../libs/dojo/dijit/themes/claro/claro.css" />
<link rel="stylesheet" type="text/css" href="../libs/dojo/dijit/themes/style.css" />
<script type="text/javascript"> djConfig = {parseOnLoad: true,} </script>
<script type="text/javascript" src="../libs/dojo/dojo/dojo.js"></script>
</head>
<body class="claro">
<style type="text/css">
#import "../libs/dojo/dojox/grid/resources/Grid.csss";
#import "../libs/dojo/dojo/resources/dojo.csss";
#import "../libs/dojo/dojox/grid/resources/claroGrid.css";
</style>
<script type="text/javascript">
dojo.require("dijit.dijit");
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ObjectStore");
dojo.require("dojo.store.JsonRest");
var store, grid;
dojo.ready(function() {
store = new dojo.store.JsonRest({
target:"jsonsource.php",
idProperty: "id"
});
grid = new dojox.grid.DataGrid({
store: dataStore = dojo.data.ObjectStore({ objectStore: store }),
structure: [
{
cells: [
[
{ name: "Id", field: "id"},
{ name: "Name", field: "name" },
{ name: "E-Mail", field: "email", width: "200px"},
]
]
}
]
}, "gridDiv");
grid.startup();
} );
</script>
<div id="gridDiv"></div>
</body></html>
jsonsource.php:
<?php
$RangeTemp = explode("=", $_SERVER['HTTP_RANGE']);
$Range = explode("-", $RangeTemp[1]);
if ($RangeTemp[1] != "") {
$RangeFrom = $Range[0];
$RangeTo = $Range[1];
}
if ($RangeFrom > 500) { print "[ ]"; die(); }
?>
[
<?php for($i=$RangeFrom; $i<=$RangeTo; $i++): ?>
{
"id": <?=$i; ?>,
"name": "Jack <?=$i; ?>",
"email": "jack#jacekplacek.pl"
},
<?php endfor; ?>
]
I believe you need to set the "Content-Range" header to let Dojo know what records you've returned, and how many there are total.
Set the header like this:
header("Content-Range: items 0-24/10000");
In your case, you would write this:
header("Content-Range: items $RangeFrom-$RangeTo/$total");
Hope that helps.
It seems that the problem is with ObjectStore + JsonRest solution. If I use
dojox.data.JsonRestStore directly it works fine.