I've made a simple ajax script (see code) which takes ID values from checkboxes that the user pressed, queries a database and construct a nested JSON-array for flot (containing one array for each ID chosen). Basically everything things work just perfect and all the arrays are being showed in the diagram. However, I'am looking for a solution to get the data, but instead of plotting them in the same diagram, I want to plot each JSON-array in the nested JSON-array in a separate diagram.
$.ajax({
type: "POST",
url: "includes/getjson.php",
data: $('.ids:checked').serialize(),
dataType: "json",
success: function(datasets){
var options = {
series: {
lines: { show: true },
points: { show: true }
},
xaxis: {
mode: "time",
timeformat: "%H:%M:%S",
twelveHourClock: true,
timezone: "browser"
},grid: {
hoverable: true,
clickable: true
}
}
$.plot($("#placeholder"), datasets, options);
}
});
I was thinking to dynamically creating the needed number of divs, maybe with a for-loop and then looping through the each array in the JSON. But I'm not sure how to do this? I could make my own parser and remove the outer-array so that I can simply split the array, but perhaps there is a better solution?
Another solution might be to make a .ajax call for each id-input from the checkboxes.
An example of an JSON where the ID are chosen can be seen here http://dinbab.dk/barline.json
Hei
I've just did something like that.
I needed a diagaram for each channel variable i had in db. What i did was putting the list of channelNames in ViewBag and used razor to create correct number of divs for the diagrams like that:
<div id="chartsDiv" class="column">
#{
int index = 0;
int heightDiv = 85 / (ViewBag.Channels.Count + 1);}
#foreach (var item in ViewBag.Channels)
{
<div id="#item.Replace(" ","")" title="#item" class="plot" style="height:#heightDiv%;"></div>
index++;
}
</div>
Then in script i do this:
var graphsArray = [];
var dataDetail;
$(function () {
var channelstxt = ('#ViewBag.ChannelsSerialized').replace(/"/g, '"')
var channels = JSON.parse(channelstxt);
var seriestxt = ('#ViewBag.SeriesJson').replace(/"/g, '"');
var seriesTab = jQuery.parseJSON(seriestxt);
$.each(channels, function (index, value) {
var elem = document.getElementById(value.toString().replace(/\s/g, ''));
var graph = $.plot(elem, [seriesTab[index]], getOptions(value));
graphsArray.push(graph)});
});
I get everything from ViewBag but you can easily get serialized json from ajax call.
I hope it helps! Ask it anything is unclear
Related
I have an array that I send from the backend, from which I create a new array of objects, for which I then use JSON.stringify to make it ready for the selectize, the array looks like this then:
[{"question":"Challenge question"},{"question":"Challenge question"},{"question":"Challenge question"}... and so on
I am trying to use that new array with selectize, but no option gets rendered:
This is the script:
var engagementsOptions = [];
icoop.engagements.map(function(item) {
engagementsOptions.push({
"question" : item
});
});
$('#engagement_question').selectize({
options: JSON.stringify(engagementsOptions),
create: true,
});
I think there is a problem with the string you are constructing for the options argument. I think it should be a comma-delimited string. Try something like this maybe (not tested with selectize, just based on the docs)?
//example data
var data_from_server = [{"question":"Challenge question 1"},{"question":"Challenge question 2"},{"question":"Challenge question 3"}];
var engagementsOptions = [];
data_from_server.map(function(item) { engagementsOptions.push(item["question"]); });
$('#engagement_question').selectize({
options: engagementsOptions.join(','),
create: true,
});
I have table that first time is server - side rendered. I want on some click event refresh data in table.
Problem is how to "bind" specific json object propertie to specific column. I receive json object with array of objects where only some of properties are interesting me.
I want
Table column -- json object propertie
ID -- id
Name -- name + surname
Cooperation -- scCooperationCollection
Skills -- scSkillsCollection
Experience -- workExperience
HTML table: http://pastebin.com/b5yRWsGe
JS reload table: http://pastebin.com/GzS8tpV6
JSON example : http://pastebin.com/AyBSrSui
See columns.data or columns.render options on how to bind source data to table columns or produce custom content for a cell.
You can access source data properties using dotted notation in columns.data or even join arrays with [] notation. For more complex data rendering like joining two fields, use columns.render instead.
For example:
var table = $('#example').DataTable({
ajax: {
url: 'https://api.myjson.com/bins/3x4ql',
dataSrc: 'aaData'
},
columns: [
{ data: "id" },
{
data: null,
render: function(data, type, full, meta){
return full['name'] + ' ' + full['surname'];
}
},
{ data: "scCooperationCollection[,].scFields.name" },
{ data: "scSkillsCollection[,].scFields.name" },
{ data: "workExperience" }
]
});
See this jsFiddle for code and demonstration.
You can navigate through the desired properties in returned json object and tie up same to your table something like below:
table.on( 'xhr', function () {
var json = table.ajax.json();
var obj = JSON.parse(json)
var tableJson = {"ID":obj.aaData[0].id};
console.log(json);
} );
Right now, I am working on my first real programming project, but right now, I ran into a problem.
I have an unordered list, with one list-item for each filter criteria. Looking like this:
<li data-xml-code="gefäße-vorhanden" class="FilterListElement">Gefäße Vorhanden</li>
<li data-xml-code="splintholz-farblich-abgesetzt" class="FilterListElement">Splintholz farblich vom Kernholz abgesetzt</li>
each of them containing an data-attribute called "data-xml-code" to make a refernce lateron possible. Another script is adding an additional class called "selected" to the list-elements which highlights them through CSS. There are about 60 different criterias to filter, so see this code as an example.
My xml structure looks like this:
<wood_data>
<wood id="fagus_sylvatica">
<name lang="de">Rotbuche</name>
<name lang="en">European beech</name>
<scientific_name>Fagus sylvatica</scientific_name>
<attributes>
<attribute>gefäße-vorhanden</attribute>
<attribute>splintholz-farblich-abgesetzt</attribute>
</attributes>
</wood>
<wood id="some_tree">
...
</wood>
</wood_data>
And there is a second list, that is directly built out of the name tags from the xml file. It creates list entries based in the id-tag of the woods in the xml as you would expect. Looking like this in the end:
<li id="fagus_sylvatica" class="WoodListElement">European beech</li>
What I am asking you is how to build a function in jQuery, that does the following:
check for all FilterListElements, that also have the class="selected" and get the "data-xml-code"-attribute from them
parse the xml, and hide every element in the WoodList, that is missing at least one of the selected filter tags.
My problem was, that I could not find a way to compare these two different sets of values. Could you please show me, how it's done?
Final solution:
Thanks a lot Shilly, I took your code and learned a lot from it. After combining it with some input from other threads, I want to present the working final code here:
function advancedFilter (){
$(this).toggleClass("selected");
activeFilters = [];
$('li.selected[data-xml-code]').map(function() {
activeFilters.push($(this).attr('data-xml-code'));
});
$.ajax({
url: 'xml/wooddata.xml',
type: 'get',
dataType: 'xml',
success: function(data) {
$(data).find('wood').each(function (){
var currentID = $(this).attr("id");
var attr = $(this).find('attributes');
//count = 0;
found = [];
attr.children().map(function(){
found.push($(this).text());
});
var diff = $(activeFilters).not(found).get();
if(diff!=0){
$('.WoodListElement[id="' + currentID + '"]').slideUp();
}else{
$('.WoodListElement[id="' + currentID + '"]').slideDown();
};
});
}
});
};
1) Get the data-xml-code selected elements. Something resembling (my jquery isn't 100%, so doublecheck if you copy/paste) :
var codes = $('li .FilterListElement .selected').map(function (el) {
return el.getAttribute('data-xml-code');
});
2) Get the value from the xml. Use tag names and nodevalue.
var xmlAttributes = function xmlAttributes( xml ) {
var attr = xml.getElementsByTagName('attributes')[0],
count,
found = [];
for (count = 0; count < attr.childNodes.length; count += 1) {
found.push(attr.childNodes[count].nodeValue);
}
return found;
};
3) You can parse each xml fragment with the function to get the list of attributes that xml has and compare it with the list of codes we extracted from the list elements, which is trivial. I'd advice saving the parsed attributes somewhere so you only have to parse the xml once. Personally, I usually cast my incoming xml to json ebfore saving it, so I have easier access to the values and only have to parse xml once for each record.
In the past I've always used this to get a hidden column's data. I would hide the column with a css class, but the responsive feature doesn't work well with these.
var td = $('td', this);
var ID = $(td[0]).text();
So I found an alternative, by hiding the columns with these classes with the responsive feature.
"columnDefs": [
//Responsive classes
{ className: 'never', targets: 0 }, //Hide on all devices
{ className: 'all', targets: 1 }, //Show on all devices
]
and then I use either one of these.
var rowData = oTable1.fnGetData(this);
var rowData = oTable1.api().row(this).data();
//Grab the first indexed item in the list
var ID = rowData[0];
That works well if you don't have an AJAX source. It will return a comma separated list of the row data. However, when I try to use this with an AJAX source I just get [object Object] back (instead of a comma separated list) if I output the rowData variable in an alert.
How do I get the row data out of a table with an AJAX source?
It seem to be stored as string so [1, 2, 3] became [object Object] when you turn it into string. Do yourString = yourList.join(',') and store yourString to keep the coma-separated string.
For an object:
yourString = (function () {
var list = [];
for(var i in yourList)
if(yourList.hasOwnProperty(i))
list.push(yourList[i]);
return list.join(',');
})();
The function is not needed, it's just to limit the variables scope.
I ended up using an answer I found here.
Converting a JS object to an array
I can pull the entire row data from the table with this.
var rowData = oTable1.api().row(this).data();
In the console log I can see that it returns a javascript object like this.
Object { id="123456", full_name="Samuel Smith", Last_name="Smith" }
I use this function to convert the object into an array.
var array = $.map(rowData, function (value, index) {
return [value];
});
In the console log, my array would appear like this.
["123456", "Samuel Smith", "Smith"]
I can then extract any item from the array like this.
alert(array[0]);
Simplifying madvora's example:
var rowData = oTable1.api().row(this).data().to$();
rowDataArray = rowData.toArray();
I have used an ajax call to retrieve data from Googles places api and I have used a for/in loop to begin to pull the information. the information that I am looking for logs to the console, but I cannot get it to display in an array how I would like it to.
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
at this point the way it is returning my data, when I run a script to pull a random string, it pulls a random letter out of the last value to be found when searching through my JSON object.
Here is my code. Not sure if I explained myself clearly but it's the best that I could word what I am looking to do. Thanks.
// **GLOBAL VARIABLES** //
// Chosen Restaurant display area
var display = document.getElementById('chosenVenue');
// Grab button
var button = document.getElementById('selectVenue');
// Sample Array that gets queried
var venueData = ["McDonalds", "Burger King", "Wendys"];
// Grab JSON data from Google
$(document).ready(function(){
$.ajax({
url: 'hungr.php', // Send query through proxy (JSONP is disabled for Google maps)
data: { requrl: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7484,-73.9857&radius=800&sensor=false&keyword=restaurants,food&key=AIzaSyBkCkXIHFjvqcqrRytSqD7T_RyFMNkR6bA&callback=?"}, // URL to query WITH parameters
dataType: "json",
type: "GET", // or POST if you want => update php in that case
success: function (data) {
// Traverse the array using for/in loop using i as var
for (var i in data.results) {
var results = data.results[i];
var nameResults = results.name;
console.log(nameResults);
var typesResults = results.types;
console.log(typesResults);
var vicinityResults = results.vicinity;
console.log(vicinityResults);
};
// On button click, randomly display item from selected array
button.addEventListener('click', function () {
console.log('clicked');
display.style.display = 'block';
//display.innerHTML = nameResults[Math.floor(Math.random() * nameResults.length)];
display.innerHTML = nameResults.toString() + "<br />" + vicinityResults.toString();
});
console.log('It is working');
},
error: function (request, status, error) {
console.log('It is not working');
}
});
});
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
Use the push method and a non-local variable:
this.nameResults = this.nameResults ? this.nameResults.push(results.name) : [];
then reference that with the Math.random method:
this.randName = function(){ return this.nameResults[Math.random() * this.nameResults.length | 0] };
References
Using Math.random flexibly
JavaScript: fast floor of numeric values using the tilde operator