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
Related
Thanks for reading my post
okay, I'm currently working on Django project that displays data in a dashboard; I manage to display and draw charts with Chart JS, great but now I need to limited number data in Django database to be displayed on charts and display the most recent data put into the database.
I use Django built-in tag to display the most recently is "last" and limiting the display data, the tag is "length_is"(Solve).
Here are my HTML codes for using the "last" tag and index page
<div class = "containor">
<div class = "float-right my-4 chartjs-render-monitor" id="chartContainerPH" style="width: 49%; height: 400px;display: inline-block; background-color:#FDFDFD;">
<center>
<a class="title-link" href="{%url 'ph' %}">PH:</a>
<p>{% for tank_system in tank %} {{tank_system.ph|last}} {%endfor%}</p>
</center>
{%include 'FrounterWeb/includes/PHchart.html'%}
</div>
This is the result I get Last Tag result in my index
(Solve)
Here' my code for chart HTML which I use the length_is tag
{%block PHchart%}
<canvas class = "my-4 chartjs-render-monitor" id="PHchart" ></canvas>
<script>
var ctx = document.getElementById("PHchart");
var PHchart = new Chart(ctx, {
type: 'line',
data: {
labels: [ {%for tank_system in tank%} "{{tank_system.datetime}}", {%endfor%} ], //x-Axis
datasets: [{ //y-Axis
label: 'PH1',
data: [ {%for tank_system in tank%} {{tank_system.PH|length_is:"3"}}, {%endfor%} ],
backgroundColor: "rgb(249, 24, 24,0.2)",
borderColor: "rgb(249, 24, 24,0.2)",
fill: true,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:false
}
}]
}
}
});
</script>
</div>{%endblock%}
and the result Length_is on chart
Summary: I can't get the built-in "filter" and "length_is"(Solve) Django tags to work. Could you please share an example or tutorial with me? The Django documentation didn't write many examples.
and here my views codes;
#login_required(login_url='/accounts/login/')
def index(request):
tank = tank_system.objects.all()
args = {'tank':tank}
return render(request,'FrounterWeb/extends/includes.html',args)
and my models' codes;
class tank_system(models.Model):
PH = models.DecimalField(max_digits=3, decimal_places=1)
EC = models.DecimalField(max_digits=3, decimal_places=1)
WaterLevel = models.IntegerField(default=100)
TempWater = models.IntegerField(default=0)
TempRoom = models.IntegerField(default=0)
datetime = models.DateTimeField(default=timezone.now())
Both of these filters are well documented in the django docs. The last filter gets you the last element of a list, and the length_is filter returns True if the list is that length, or False otherwise.
This likely means that there is an issue in your understanding of your code. You'll want to verify the type and the values of tank_system.PH or tank_system.ph (you have both) and the case will matter. One way to debug this is to simply output the value of tank_system.ph to the web page and verify the result.
My Rails website display a simple table about name and age of students.
name age
Lily 25
Tom 27
Chris 19
...
So I have #names = Student.pluck(:name), #ages = Student.pluck(:age). Now I would like to generate a line chart by using Highcharts:
HTML: <div id='students-chart'></div>
JavaScript:
$(function() {
Highcharts.chart('students_chart', {
...
};
};
Now I should provide the name and age to the chart as the xAxis and yAxis. The simplest way is to include the JavaScript in the html.erb file and provide the data by <%= #names %> and <%= #ages %>. However, it's not recommended, and I want to put the JavaScript code in the assets/javascripts/students.js file.
A very common way to fetch the data in the JavaScript file is using the Ajax, however, my data is already in the page so I don't want to add an extra action in the controller to send the data.
So what's the best practice to get the data for the Highcharts? data- attribute?
No front-end frameworks in the project, only jQuery. I know some gems could help me like Chartkick or LazyHighCharts, but I would like to know the basic strategy.
This is one way to show the chart, just jQuery getting data from the controller.
In controller fetch the data, adjust and convert to json. Customise respect to on your models. Here is an example with an array of hashes (data are passed as arrays):
#series = [ {name: 'Lily', data: [25]}, {name: 'Tom', data: [27]}, {name: 'Chris', data: [19]} ].to_json
For example, if your User model includes the age column, you can adjust like this:
#series = User.all.map{ |user| {name: user.name, data: [user.age]} }.to_json
In view (customise as you will), passing the variable here:
<div id='students_chart'></div>
<script>
$(function () {
var myChart = Highcharts.chart('students_chart', {
chart: {
type: 'column'
},
title: {
text: 'User ages'
},
xAxis: {
categories: ['Users']
},
yAxis: {
title: {
text: 'Age'
}
},
series: <%= raw #series %>
});
});
</script>
Edit - get data from server
Instead of sending data to view, render as json (no need to add e new action):
respond_to do |format|
format.html
format.json { render json: #series }
end
Then place the javascript in a file and get json data using jQuery.getJSON():
$.getJSON(window.location.href, function(json) {
var highChartData = json;
console.log(json)
var myChart = Highcharts.chart('students_chart', {
chart: {
type: 'column'
},
title: {
text: 'User ages'
},
xAxis: {
categories: ['Users']
},
yAxis: {
title: {
text: 'Age'
}
},
series: highChartData
});
});
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.
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 am trying to submit an aria template form http://ariatemplates.com/,the submission is done to a Spring MVC controller/servlet.
The form is getting submitted all right but i am not able to get the values of the aria elements like date picker,text box etc in the controller.
Request.getParameter is of no use.
Any Help will be appreciated.
Here is my sample tpl file,js file and the Spring Controller.
TPL File
{Template {
$classpath:'view.Turnover',
$hasScript : true
}}
{macro main()}
<form action="test.do" method="POST" id="turnoverform">
<div style="float:left;padding-top: 3em;padding-bottom: 3em;padding-right: 3em;">
{#aria:Div {
sclass : "basic",
width : 740,
height : 300
}}
<p style="font-family:Arial,Helvetica,sans-serif;font-size: medium;">Create Turnover Report</p>
<hr />
{#aria:DatePicker {
label: " begin date:",
labelWidth:190,
width:330,
helptext:"Type date or select",
}/}
{#aria:DatePicker {
margins:"x x x 20",
label: "end date:",
labelWidth:190,
helptext:"Type date or select",
width:330,
}/}
<br/>
<br/>
<br/>
{#aria:TextField {
label : "User id",
labelPos : "left",
helptext : "ID",
width : 250,
block : true,
labelWidth : 80,
bind : {
"value" : {
inside : data,
to : 'value' }
}
}/}
<br />
{/#aria:Div}
<br />
{#aria:IconButton {
icon: "std:confirm",
label:"Create",
width : 300,
tooltip : "Click on this to create a Report",
block: true,
onclick : {
fn : buttonClick
}
} /}
</div>
</form>
{/macro}
{/Template}
Javascript File :
Aria.tplScriptDefinition({
$classpath : "view.TurnoverScript",
$prototype : {
/**
* Callback for the click event on the first button.
* #param {aria.DomEvent} evt Click event
*/
buttonClick : function (evt) {
aria.core.IO.asyncFormSubmit({
formId : "turnoverform",
callback : {
fn : this.onSuccess,
onerror : this.onError,
scope : this
}
});
},
onSuccess : function (evt, args) {
alert("The Template has been created");
//this.$json.setValue(["view:Dialog"], "dialogOpen", true);
},
onError : function (evt, args) {
alert("The Template has not been created due to some Error");
}
}
});
in Aria Templates you don't work normally with DOM elements but with the data model.
The way to achieve what you want is to bind those values to the datamodel using the bind property
{#aria:DatePicker {
label: " begin date:",
labelWidth:190,
width:330,
helptext:"Type date or select",
bind : {
value : {
inside : data,
to : "begin_date"
}
}
}/}
Your datamodel would now contain those values, try to modify those values and see the content of this.data in your template script.
To submit the data you have two options,
Template Script through aria.core.Io.asyncRequest (or maybe the RequestMgr, depending on your application complexity).
This method takes a data string that in case of POST requests is the message body. It has to be a string so you can use aria.utils.json.JsonSerializer.serialize() to convert your datamodel into a string.
aria.utils.json.JsonSerializer.serialize(this.data, config)
In the previous snippet of code config is optional, if provided it should match this bean.
Module controller through submitJsonRequest
The good thing about using a controller is that you separate the logic of connecting to a server from the template and that you can send directly an object as data, serialization is done internally.
The drawback is that you'll probably have to configure your UrlService to convert actions to actual URL. Few more info here