flot gets the data from json but shows blank graph - flot

This is the code, when i mannually paste the json data inplace of series the graph is obtained but through ajax call am able to get the json data but the chart is blank.
$(document).ready(function(){
$.ajax({
url:"sqljson.php",
method:"GET",
datatype:"json",
success:graph
})
function graph(series){
var data=series;
alert(series);
var options={
lines:{show:true},
points:{show:true,hoverable:true},
grid:{hoverable:true,clickable:true}
}
$.plot($("#place"),[data], options);
}
});
json data:obtained on the alert window
[["253","5"],["254","32"],["255","10"],["256","50"],["257","1"],["258","2"["259","100"],["260","38"],["261","2"],["262","20"],["263","2000"],["264","500"], ["265","400"],["266","10"],["267","50"],["268","9"],["269","200"],["270","40"]["271","700"],["272","188"],["273","73"]]

As per the Flot FAQ:
Q: Flot isn't working when I'm using JSON data as source!
A: Actually, Flot loves JSON data, you just got the format wrong.
Double check that you're not inputting strings instead of numbers,
like [["0", "-2.13"], ["5", "4.3"]]. This is most common mistake, and
the error might not show up immediately because Javascript can do some
conversion automatically.
You need to change your output JSON so there are no quotes, i.e.:
[[253,5],[254,32],[255,10],[256,50],[257,1],[258,2],[259,100],[260,38],[261,2],[262,20],[263,2000],[264,500],[265,400],[266,10],[267,50],[268,9],[269,200],[270,40][271,700],[272,188],[273,73]]
However, this may not do it, it needs to be in a format similar to this, so:
{
"label": "example",
"data": [[253,5],[254,32],[255,10],[256,50],[257,1],[258,2],[259,100],[260,38],[261,2],[262,20],[263,2000],[264,500],[265,400],[266,10],[267,50],[268,9],[269,200],[270,40][271,700],[272,188],[273,73]]
}

Related

Mutator runs on update but cell data unchanged

I want to create a new field reservationAction and put into my table as a column Reservation defined as:
{title: "Reservation", field: "reservationAction", mutator: reservationMutator},
with reservationMutator as:
var reservationMutator = function(value, data, type, params, component) {
console.log(data);
if (!data.checkoutable) return null;
if (data.is_reserved) {
return "Free";
}
return "Get";
}
is_reserved and checkoutable are pre-existing fields of my data.
When the page initially loads, and table is created using ajax, the cell shows the correct string for Reservation. When is_reserved is changed server-side, I call table.updateOrAddData([newData]) (as part of websocket event-handler).
The problem:
When table.updateOrAddData([newData]) run, I can see the custom mutator get triggered
and from the console.log() line, see that the reservationAction is correctly set in the log. But the table itself is showing the old value. Other (non-mutating) columns are updated on the table as expected. Am I missing something or is this a bug?
If instead I use table.replaceData(), then both console, and table show correct value. But I would want to avoid doing this on each websocket event for performance reasons.
Version: I've tried all 5+.
Any help would be appreciated!
jsfiddle
Don't know if this is a workaround or how I'm actually supposed to do it in the first place but, doing row.reformat() seems to do what I expect. Oh well.
table.updateOrAddData([row_obj])
.then(function(rows){
rows.forEach(row => {
row.reformat();
});
});

After passing object to handlebars, how can I access that object in script tag?

I first get the data from sql then pass it into handlebars.
Inside the tag in .handlebars/using view.js, I want to access doctors, but i keep getting[object][object]. I tried json.stringifying it before but still no luck. What is the best way to do this?
umd.matchDocs(val2, function(data) {
console.log(data);
var renderDocs = {
doctors: data
}
res.render("dashboard", renderDocs);
});
After passing object to handlebars, how can I access that object in script tag?
No, not by default. But you can make the data available manually if you want.
Data you pass to handlebars rendering operation is available during the rendering operation only. If you want to be able to access some of that data later in client-side <script> tags, then you can "render" Javascript variables into the <script> tags that contain the desired data.
Remember when rendering data into Javascript variables, you need to render the actual Javascript text (converting to JSON will often create the text for you).
In your specific example, you could do something like this in your rendering code:
umd.matchDocs(val2, function(data) {
console.log(data);
var renderDocs = {
doctors: JSON.stringify(data)
}
res.render("dashboard", renderDocs);
});
And, then in the template:
<script>
var doctors = {{{doctors}}};
</script>
Then, this array of doctors would be available to the Javascript in your page.
In case you haven't seen the triple braces like shown above, that's to tell handlebars to skip any HTML escaping in the data (because this isn't HTML).

Can Cloudant list/show functions return objects and arrays(any JSON)?

As per the API documentation for Cloudant: Show function can be used to render a document in a different format or extract only some information from a larger document. Same is the case for a list function, the only difference is that it applies on a set of documents. I created a design document with a show function as follows:
{ "shows": { "showDemo":"function(doc,req){return {'body': doc, 'headers':{'Content-Type':'application/json'}}}" } }
When I use this function, _design/showFunc/_show/showDemo/doc1, I get the following error:
{ "error": "unknown_error", "reason": "badarg", "ref": 1793182837 }
I have observed the same error when the show function returns an array. However, no error is given when HTML,Text, XML is returned. Can we say that list/show functions can only return data in a format other than JSON? This example shows the "Accept" header for req object request Object.
What's happening here is that the show function needs to return a response object. From the docs (see http://docs.couchdb.org/en/2.1.0/json-structure.html#response-object) the body field needs to be a string, so you can return whatever you like but it needs to be stringified or otherwise turned into a format that can be sent as HTTP.
If you want to send JSON then doing JSON.Stringify(doc) as the value for body should do what you expect.

Dynamically refresh a div without a straightful DOM manipulation

I have to update for example a table, a list if some values. I can insert new values and try to reload a entire page to show table or list values again.
If I give a try on Ajax updates I have to manipulate DOM, creating a bunch of new tags, concatenate and inject the new HTML on old one. This not a painful way, you even must re-type the code created before to exhibit new entries.
E.g: this is a fictitious example and illustrates what I mean:
$.ajax({
url: '/post/addComment/',
type: 'POST',
data: 'comment=' + comment,
beforeSend : function() {
//waiting message
$('#some_information_div').html('<strong>Updating...</strong>');
}
}).done(function(data) {
//new data comes here (by JSON, plain text, whatever...)
if (data.status == 'OK') {
//OHHH MAN WE HAVE TO POPULATE MANUALLY IT AGAIN
var c = '';
c = '<table>'
data.content.forEach(function(e) {
c += '<tr><td>' + e.name + '</td></tr>';
});
c += '</table>'
//update with new values
$('#some_information_div').html('');
$('#destination_table').html(c);
}
});
Unfortunately I have to do all the time with my lists and tables and somehow I have to re-type codes and manipulate it all by the javascript. I figured out something might be useful like does jQuery.load(), maybe it can fit what I want to, I have not tried it.
Some other languages and frameworks like JSF do it easily with "render technique", you directly update content without have to create and manipulate DOM in manually way.
Please, any kind of suggestion, any clue to this approach will be very helpful.
P.S.: The code sample tag doesn't work well here.
This can be done by using .load() jquery function. I have illustrated for some page 1.php and some table having id mytable
$('table#mytable').load('./1.php #mytable');
for constant refreshing --
setInterval(function() {
$('tablev#mytable').load('./1.php #mytable');
}, 5000);

When no data is returned from database

I am intiating a loading panel in init method and hiding it in ReturnDataPayload event.This is working perfectly when data Table has got some values in it.But when there is no data returned from database , the control is not going to returnDataPayLoad event.Please help me in finding an event which will be fired even when the response doesn't have any data or tell me a way to hide the loading panel.
If you want a custom behavior, use DataSource's sendRequest method of the dataTable's dataSource
(function() {
var YdataTable = YAHOO.widget.DataTable,
YdataSource = YAHOO.util.DataSource;
var settings = {
container:"<DATATABLE_CONTAINER_GOES_HERE>",
source:"<URL_TO_RETRIEVE_YOUR_DATA>",
columnSettings:[
{key:"id", label:"Id"}
],
dataSourceSettings:{
responseType:YdataSource.TYPE_JSON,
responseSchema:{
resultsList:"rs",
fields:[
{key:"id"}
]
}
},
dataTableSettings:{
initialLoad:false
}
}
var dataTable = new YdataTable(
settings.container,
settings.columnSettings,
new YdataSource(
settings.source,
settings.dataSourceSettings),
settings.dataTableSettings);
})();
keep in mind No matter which source is your data: XML, JSON, JavaScript object, TEXT, you always will get your data in a unified way through DataSource's sendRequest method. So when you want to retrieve your data and, at the same time, add custom behavior, use it
dataTable.getDataSource().sendRequest(null, {
success:function(request, response, payload) {
if(response.results.length == 0) {
// No data returned
// Do what you want right here
// You can, for instance, hide the dataTable by calling this.setStyle("display", "none");
} else {
// Some data returned
// If you want to use default the DataTable behavior, just call
this.onDataReturnInitializeTable(request, response, payload);
}
},
scope:dataTable,
argument:dataTable.getState()
});
The properties of the response are
results (Array): Your source of data in a unified way. For each object in the results Array, There is a property according to responseSchema's fields property. Notice i use response.results.length to verify if some data has been returned
error (Boolean): Indicates data error
cached (Boolean): Indicates cached response
meta (Object): Schema-parsed meta data
On the YUI dataTable page, look for Loading data at runtime to see some built-in functions provided by YUI dataTable
I hope it can be useful and feel free to ask for help for anything else you want about YUI. See a demo page of nice features of YUI dataTable

Resources