jqPlot charts on page load - html

I have a form where I select the number of items. Upon clicking submit, it should take me to a new page where it would display the item selected and depending on the number of items selected, it would create those many jqPlots, one for each item.
Any suggestions on how do I go about doing this?
Thanks,
S.

It's hard to give any specifics without more detail about the items, but basically you would pass a JSON structure to your view with the items to be plotted. Then you would loop through the JSON structure, creating DIV tag for each item to be plotted and appending the DIV tags to the body.
The Javascript part would look something like this:
$.each(items, function(index, value) {
$myPlot = $("<div>");
$myPlot.attr("id", "item"+index);
$.jqplot($myPlot.attr("id"), ...);
$("body").append($myPlot);
});

This question is very general, but answering (specifically and only) the question of loading multiple charts:
You need a unique HTML div id for each chart; consider using an RFC 4122 UUID (generate as needed) for each chart/div rather than a sequential index for each. Use something that looks like this as a placeholder div for each:
<div class="chartdiv" id="chartdiv-${UID}">
<a rel="api" type="application/json" href="${JSON_URL}" style="display:none">Data</a>
</div>
This embeds the JSON URL for each div inside it, in a hidden hyperlink that can be discovered by JavaScript iterating over your multi-chart HTML page.
The matter of the UUID is inconsequential -- it just seems the most robust way to guarantee a unique HTML id addressable by JavaScript for each chart.
Subsequently, you should have JavaScript that looks something like:
jq('document').ready(function(){
jq('.chartdiv').each(function(index) {
var div = jq(this);
var json_url = jq('a[type="application/json"]', div).attr('href');
var divid = div.attr('id');
jq.ajax({
url: json_url,
success: function(responseText) { /*callback*/
// TODO: responseText is JSON, use it, normalize it, whatever!
var chartdata = responseText;
jq.jqplot(divid, chartdata.seriesdata, chartdata.options);
}
});
});
});

Related

Dynamically display a list of xml hotspots (for krpano) based on json list

A bit of a newbie question for xml/krpano,
I have a list of json items that I want to be dynamically loaded into XML <hotspots>. I can loop through each item in JavaScript but I have no clue how to do the same loop in XML!
Check out this picture:
Imagine that each rectangle with an image is one item in a JSON list. Each rectangle you see is a <hotspot>. Right now these three hotspots are hardcoded into the XML file, but I want to dynamically load hotspots based on how many JSON list items exist.
Here is one hotspot. If my json list has 16 items, I would expect 16 hotspots
to be loaded.
<!--* video image thumbnail *-->
<hotspot name="start" distorted="true"
url="/panorama/%$panoId%/thumb.png"
ath="0" atv="0"
ox="0" oy="36"
vr_timeout="2000"
zorder="99"
scale="0.8"
onclick="changepano( loadscene(video_scene, null, MERGE|KEEPVIEW|KEEPMOVING, BLEND(1)); );"
alpha="0.0"
onloaded="if(vr_start_done === true, removehotspot(start); start_vr(); , tween(alpha,1); );"
/>
Your question is about dynamically generating hotspots in KRPano from a JSON list.
It is not really clear to me the way you wrote your question if you want to read the JSON from KRPano XML file (let's say FROM KRPano) or if you are expecting to use Javascript to ask KRPano to produce the hotspots.
These are two completly distinct ways of doing it :)
Because I'm lazy and I suppose you want to deal with JSON in JS, I go for this solution...
Loading a JSON file from Javascript
Your KRPano project should look like a core HTML file presenting Javascript to embed the KRPano plugin.
There, you can declare a script content in your HTML in which you will parse your JSON content and you ask KRPano to generate a hotspot. This method should be called when you are sure KRPano is ready, or get it called from KRPano when it is ready, using "onready" attribute.
myHotspotList.json content:
var myHotspotList = [
{
name: "myFirstHotspot",
atv: 15.0,
ath: 56.5686,
url: "myHotspotImage.jpg"
}
];
tour.html content:
<html>
...
<script url="myHotspotList.json'></script>
<script>
function generateHotspots() {
// First, we get the KRPano plugin
var myKRPano = document.getElementById('krpanoSWFObject');
// Now we parse the JSON object
for(var idx in myHotspotList) {
// Get the current Hotspot data
var currHotspot = myHotspotList[idx];
// Ask KRPano to create a hotspot with our current name
myKRPano.call("addhotspot('"+ currHotspot.name +"');");
// Now set various attributes to this hotspot
myKRPano.call("set(hotpost['"+ currHotspot.name +"'].atv, "+currHotspot.atv+");");
myKRPano.call("set(hotpost['"+ currHotspot.name +"'].ath, "+currHotspot.ath+");");
myKRPano.call("set(hotpost['"+ currHotspot.name +"'].url, '"+currHotspot.url+"');");
}
}
</script>
...
// When you ask for pano creation, give your generation method as callback
embedpano({target:"krpanoDIV", onready:generateHotspots});
...
</html>
I hope this help and you got the trick with calling JSON object attributes and all.
Regards

angularjs save rendered values in html in a variable

I hope someone can help me with this, It's a strange question maybe as I didn't find an answer online.
I call the database and retrieve a list (in json) of items.
Then in angularjs,I render this list by extracting relevant pieces of data(name,age,etc) and show it properly in a table as a list of rows.
I have then an edit button that takes me to another page where I want to put a dropdown list.
What I want to know if is possible to add to that dropdown list the rendered list I previously created in my previous page.
is it possible to save the previously rendered list in a variable and then use that variable in the dropdown?
thank you
You could store the list within a controller and make this data availablte to this dropdown, I think.
Instead of trying to query for the list, add the list to the template, get the list from the template and render somewhere else, I'd suggest query for the list, save the list in a service , and then when you want to use that list again, get it from the service. Something like:
service:
var services = angular.module('services');
services.factory('getListService',['$http',function($http){
var getListOfStuff = function(){
//call to database
return //your json
};
var extractNameAgeEtc = function(){
var myListOfStuff = //get list of stuff from $http or database
var myListOfNameAgeEtc = //make a list of tuples or {name,age,etc} objects
return myListOfNameAgeEtc;
};
return {
extractNameAgeEtc : extractNameAgeEtc
};
}]);
controllers:
angular.module('controllers',['services']);
var controllersModule = angular.module('controllers');
controllersModule.controller('tableRenderController',['getListService','$scope',function(getListService,$scope){
//use this with your table rendering template, probably with ng-repeat
$scope.MyTableValue = getListService.extractNameAgeEtc();
}]);
controllersModule.controller('dropdownRenderController',['getListService','$scope',function(getListService,$scope){
//use this with your dropdown rendering template, probably with ng-repeat
$scope.MyDropDownValue = getListService.extractNameAgeEtc();
}]);

HTML Form - submit array of ID's of selected divs

I have an array of divs which can be selected (change background colour on click to signify that to the user).
I want a way to submit the ids of all of these divs to my app, though can't see a 'nice' way of doing this; at the moment the only thing I can see to do is have a button that onclick triggers a javascript function that gets the id's and sends them back to my server in a POST.
Is there a way of creating a multiple select input on a form which uses divs instead of checkboxes or a multi-select list, or a better way of doing what I'm attempting?
Assuming you add the class selected when a user 'selects' the div:
var data = {};
$(".classOfDivs.selected").each(function(){
data[$(this).prop('id')] = 'true';
}
$.ajax({
url : 'ajaxPage.php',
type : 'POST',
dataType : 'text',
cache: false,
data: data,
success : function(text){alert('Saved: '+text);},
error: function(){alert('Did not reach server');}
});
Use the success function to process the returned text as needed. dataType can be changed to html, JSON, etc. See the .ajax() documentation.
Have a hidden input for each div, all with the same name but with a different id. When a div is clicked update the corresponding hidden input with the id. Then when you submit through a standard form POST all of those values will be available through the name you specified.
Since this is an app, what you could do is store everything in HTML5 localstorage using the JQuery javascript library.
Here's how to do it step by step:
Create a jquery array
on click, get div id and store it in the array with a key/value pair
if clicked again, remove it from the array
have some event listener like a "submit" button to store the value of your array to localstorage
Here is a jsfiddle I had that has exactly what you are talking about: http://jsfiddle.net/CR47/bqfXN/1/
It goes into a little more depth but the jquery should be exactly what you need.
The reason this is better than submitting with POST or using ajax is because since you say this is an app, you will be able to use this method offline, where as post or ajax would require a connection to a server running php.
var skinCare=[]; //the array
$('.skinCare').click(function(){ //onclick
var value = event.target.className.split(" ")[0]; //get classname, you would get id
var index = skinCare.indexOf(value); //gets where the location in
//the array this code is
if($(this).hasClass('selected')){ //when a div is clicked it gets
//$('.skinCare').removeClass('selected'); //the class "selected" and adds
skinCare.splice(index, 1); //to array, then another click
} else if($.inArray(value, skinCare) == -1){ //removes it from array
skinCare.push(value);
}
});
$('.submitbutton').click(function(){
localStorage.setItem('Skin Care', JSON.stringify(skinCare));
});

Display data in dojo

I have an XML file that contains one set of data and this has to be represented in one of the many dojo content panes of a HTML page. I've tried dojox.grid.DataGrid and it works; however since the data grid is used to generally represent tabular data, I don't want to use data grid.
Is there any other way to represent this data in a simple format?
The XML file is something like this:
<Summary>
<neName>abc</neName>
<neType>pqr</neType>
<neRelease>2.0</neRelease>
<neAddress>10.10.82.105</neAddress>
<supervisionState>SUPERVISED</supervisionState>
<operationalState>ENABLED</operationalState>
<alignmentState>ALIGNED</alignmentState>
<criticalAlarms>0</criticalAlarms>
<majorAlarms>0</majorAlarms>
<minorAlarms>0</minorAlarms>
<noOfShelves>5</noOfShelves>
</Summary>
I want this data to be represented something like this:
From what you want the data to look like, I would go for basic css styling of HTML elements rather than any widget.
You can use dgrid however,
check:
https://github.com/SitePen/dgrid/
http://www.sitepen.com/blog/category/dgrid/
If you're feeling frisky, you can make a sort-of generic, XML data widget. Here's an example I have from some time ago.
dojo.declare("foo.XmlDisplay", dijit._Widget, {
postCreate: function()
{
this.inherited(arguments);
dojo.xhrGet({
url: this.href,
handleAs: "xml",
load: dojo.hitch(this, "setData")
});
},
setData: function(data)
{
// All items with a xmldisp-tag attribute should get data
dojo.query("*[data-xmldisp-tag]", this.containerNode).forEach(
function(item) {
var tag = dojo.attr(item, "data-xmldisp-tag");
var value = data.getElementsByTagName(tag);
if(value.length == 1) item.innerHTML = value[0].textContent;
else console.warn("No data in xml for",tag);
}
);
}
});
You can then use it something like this in your HTML (i.e. the widget doesn't care how you display the data, it just uses the given tag names to lookup data in the XML from the server):
<div data-dojo-type="foo.XmlDisplay" href="/MyXmlStuff?id=42">
<dl>
<dt>NE name</dt><dd data-xmldisp-tag="nename">-</dd>
<dt>NE type</dt><dd data-xmldisp-tag="netype">-</dd>
</dl>
<dl>
<dt>Alarms</dt><dd data-xmldisp-tag="majoralarms">-</dd>
<dt>Minor</dt><dd data-xmldisp-tag="minoralarms">-</dd>
</dl>
</div>
Here's a modified jsfiddle you can try: http://fiddle.jshell.net/K4UnJ/3/
Not sure if this fits your task at all, but since I had very similar code lying around, I thought I'd share.

pre-load search query to link from table and pass it to ajax

So I currently have a table that's generated by ajax and json file.
The table has 3 segments, a name, an ID and the third column is a link for more details of each result.
Example of how my table looks
PATO:0001243 light blue Details
PATO:0001246 light brown Details
PATO:0001247 light cyan Details
the current code I have to generate the table is:
$.each(data.matches, function(i, item){
var this_row_id = 'result_row_' + next_row_num++;
$('<tr/>', {"id":this_row_id}).appendTo('tbody');
$('<td/>', {"text":item.label}).appendTo('#'+this_row_id);
$('<td/>', {"text":item.value}).appendTo('#'+this_row_id);
$(''+ 'Details' +'').appendTo('#'+this_row_id);
});
Ideally, I would like to be able to click on the "Details" and it would pass the ID value to another ajax call and then create a dialog/modal to display the results of that ajax call.
EXAMPLE
From the list above, clicking on "Details" from the first entry will pass the values "PATO:0001234" to my "test.cgi" script which will use that value to process and spit back out a JSON for me to display in a dialog.
I'm not asking for someone to write my code for me, just some direction about how to approach this.
I think I'm probably wrong to link directly to my cgi script from the <a href>. But I don't know how to link that to an ajax call from a text link.
Update
Left the page loaded too long; #floatless has posted a cleaner approach with chaining, didn't think of that.
You could change the last few lines to something like what's below. The idea is to attach a handler to each link when it's created which will call the loadDetail function with the appropriate item label. In loadDetail, it's then a simple matter of making an ajax request with the label as the parameter.
Note that you don't need to use ./test.cgi - test.cgi will suffice.
...
$(''+ 'Details' +'').appendTo('#'+this_row_id);
$('#detail_' + this_row_id).click(loadDetail(item.label));
}
function loadDetail(label){
$.get('test.cgi', {label: label}, function(data){
//create your dialog to display the response data
});
}
You could append click event handler while generating table:
$(''+ 'Details' +'').appendTo('#'+this_row_id).click(function()
{
$.getJSON("./test.cgi", {label: item.label}, function(data)
{
//Do something with received data
});
return false;
});