JSON data populating only with first letter in DataTable - javascript

I am using the Rasa X HTTP API to parse a yaml file and convert to a JSON object. I want to take this JSON object and then send it to my datatable to populate the rows. The problem is when I populate the datatable when calling the function in my datatable javascript, the JSON returns like this:
The API according to the docs here turns the payload into JSON format: https://rasa.com/docs/rasa-x/pages/http-api#operation/getDomain
Here is my code for the HTTP API:
export function getDomain(token) { //used to get auth token which is recreated each instance
var data = ""
//console.log(token);
var header_data = { Authorization: "Bearer " + token }
//console.log(header_data);
var sendData = {} //data to send. Check Rasa x API doc
$.ajax({
url: 'http://localhost:5002/api/domain',
type: 'GET',
async: false,
headers: header_data,
success: function (resp) {
//put name of json value you want to read after 'resp.'
//console.log(data);
var jsonDomain = yaml.parse(resp);
data = jsonDomain.entities;
console.log(typeof (data));
return data;
},
error: function (error) {
console.log('Error ${error}');
}
});
return data;
}
This function above parses the yaml file to get the data
export function getAuth() { //used to get auth token which is recreated each instance
var data = "";
var sendData = { "username": "me", "password":"huiwehfuiwfa" } //password changes each instance, there is a way to create a constant one too
$.ajax({
url: 'http://localhost:5002/api/auth',
//projects/default/intents',
type: 'POST',
async: false, //depracted but needs to be included to have it work
headers: {
"Access-Control-Allow-Origin": "*"
},
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(sendData),
success: function (resp) {
data = resp.access_token; //put name of json value you want to read after 'resp.'
return data;
},
error: function (error) {
console.log('Error ${error}');
}
});
return data;
}
This function gives authorization to use the API, gets the datatype as JSON, and stringifys it.
The console log for this shows as an object:
(3) ["plant", "water", "temperature"]
0: "plant"
1: "water"
2: "time"
length: 3
I then call this function to be able to use the data from the API in my datatables javascript:
import { getAuth, getDomain } from "./yaml.js";
export function populateTable() {
var token = getAuth();
var table_data = getDomain(token); // this gets the JSON data
var ieColumns = [{
title: "Name",
type: "text"
}];
var E = $('#Forestry').DataTable({
"sPaginationType": "full_numbers",
data: table_data,
columns: ieColumns,
dom: 'frtBip', // Needs button container
select: 'single',
responsive: true,
altEditor: true, // Enable altEditor
buttons: [
{
text: 'Add',
name: 'add' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Edit',
name: 'edit' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Delete',
name: 'delete' // do not change name
}
], style: "width:100%"
});
When I try to parse the JSON data using the parse function, I get an error from datatables complaining it is not in valid format.
I have also wrapped the function call getting the data from the API in brackets like this
var table_data = [getDomain(token)]; // this gets the JSON data
This returns one row with the first element in the JSON object which is plant but not the others.
The object type this returns is an array(3).
I want it to return each element in a separate row.

Related

Kendo Grid Destroy Command sending entire HTML page to schema response -- Uncaught TypeError: Cannot read property 'results' of undefined

I am trying to add a Delete button to each row in my kendo grid. I added the destroy command to the grid configuration and have the Delete button showing, but when I click it, I receive a console error -- Uncaught TypeError: Cannot read property 'results' of undefined. This is referring to a line in the schema.parse that reads:
for (var i = 0, il = response.d.results.length; i < il; i++)
It's saying response is undefined. when I console.log(response) and it turns out that the entire html page is being sent in the response.
This doesn't make sense to me, because when I console.log(options) in transport.destroy and console.log(data) in the parameterMap, both console.logs show me in JSON format the row that needs to be deleted and includes the ID.
So why is it being transported to the schema as the entire html page? console.log(response) in the schema starts with <DOCTYPE !HTML> etc. and includes the whole page. Can anyone tell me why this is?
and yes, I have already included editable: "inline" in the grid configuration. Thanks
var ds = new kendo.data.DataSource({
transport: {
read: {
url: function () {
***omitted for privacy, but read works. the grid loads fine***
},
cache: false,
type: 'GET',
headers: {
'Accept': 'application/json; odata=verbose'
}
},
destroy: {
url: function (options) {
console.log(options);
console.log("destroy command called");
}
},
parameterMap: function (data, type) {
console.log(data);
console.log(type);
if (type == "destroy") {
// send the destroyed data items as the "models" service parameter encoded in JSON
return { models: kendo.stringify(data.models) }
}
}
},
pageSize: 10,
sort: {
field: "Modified",
dir: "desc"
},
filter: {
logic: 'and',
filters: [{
field: 'State',
operator: 'eq',
value: 'Submitted'
}]
},
error: function (e) {
kendo.alert(e.errors);
},
schema: {
errors: "error",
parse: function (response) {
console.log(response);
var data = [];
for (var i = 0, il = response.d.results.length; i < il; i++) {
var item = response.d.results[i];
//Create new fields to handle filtering by Date (instead of DateTime)
item.ModifiedFilter = new Date(new Date(item.Modified).setHours(0, 0, 0, 0));
item.CreatedFilter = new Date(new Date(item.Created).setHours(0, 0, 0, 0));
data.push(item);
}
return data;
},
total: function (response) {
return response.length;
},
model: {
id: 'Id',
fields: {
```
The dataSource.destroy.url handler should return the url which the grid will request for the destroy operation. As in your case the destroy.url handler does not return anything, the "" url is requested, which is equivalent to requesting your landing page, thus, HTML is returned.
If you do not intend to update the server on delete and just visually remove the row, simply define the destroy as a handler which does nothing.
e.g.
destroy: function (options) {
options.success(options.data.models);
}

Display data from json array using ajax

I have the following code on index page the script contains part of the code that will call the data from test page
<div class="leftbox" id="proddisplay">
</div>
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
From test.php i am getting json array that looks like this
[1,2,"text","text2"]
I want to display the json array data in a tabular form and display it inside the div. the view of table should be something like this (it will have some css of its own)
static text: 1
static text: 2
static text: text
static text: text2
static text will be given by me and remains the same throughout however the values of array would change. can anyone tell how i can do so
individually i can display the data from json, but here i also need to put json data in a table and then put that table within a div
First of all you need to encode the array in php before sending to frontend, use json_encode() and then decode it in the success function using JSON.parse() . After just run a loop throught the array.
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
var returneddata = JSON.parse(returndata);
var htmlData= '';
for(var i=0; i<returneddata.length; i++){
htmlData+= 'static text: '+returneddata[i]+' <br>';
}
$('#proddisplay').html(htmlData);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});

Backbone.js Unable to parse response from collectio.toJSON()

I am learning Backbone and it would be great if someone can help me with this issue. After I do a fetch on my collection, in success callback I get the parsed data using collection.toJSON(), this actually returns an object and I am unable to get anything out of this object. This object actually has data that I need.
My question is how do I access rows property in my object. Here is my code for your reference
var testCollection = Backbone.Collection.extend({
model:myModel,
url: '/myApiEndPoint',
data: '',
initialize: function(models, options) {
this.data = models.data;
},
fetch: function(options) {
var ajaxConfig = {
url: this.url,
data: this.data,
type: 'POST',
dataType: 'text',
contentType: 'text/xml',
parse: true
};
options = _.extend({}, ajaxConfig, options);
return Backbone.Collection.prototype.fetch.call(this, options);
},
parse: function(xmlResponse) {
// I have some parsing logic to extract uid and rows from my xmlResponse
return {
uid: uid,
rows: rows
};
},
});
var collObj = new testCollection({data: xmlQuery1});
collObj.fetch({
success: function(collection){
// This code block will be triggered only after receiving the data.
console.log(collection.toJSON());
}
});
As the name toJSON suggests, it returns you the array of JSON objects where each object is a Model's JSON object. You can fetch the required properties in this way:
collObj.fetch({
success: function(collection){
// This code block will be triggered only after receiving the data.
console.log(collection.toJSON());
var uid = 'uid-of-an-object-to-access';
var rows = collection.get(uid).get('rows');
console.log(rows);
}
});

JQPlot, JSON and 'No data specified' Error

I am trying to use JQPlot within a VB.NET application under .NET 3.5. On a button click, using jquery, I am trying to populate the JQPlot Chart with JSON derived data using a ASP.NET Webservices Source file (which is part of the solution).
The JSON data is sent by the web service but when it is presented to JQPlot I get the javascript error 'No Data Specified' which is generated by JQPlot code.
My code listing is as follows:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
Javascript code outside the 'document.ready' function:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
//url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
var ret = response.d;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
return ret;
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var jsonurl = "./jsondata.txt";
function getElectricDataJSON() {
var ret = ajaxDataRenderer();
var plot1 = $.jqplot('chart2', jsonurl, {
title: "AJAX JSON Data Renderer",
dataRenderer: ret, //$.jqplot.ciParser
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
}
The JSON data format is as follows:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220429.41 }, ... ]
Any help or advice will be appreciated.
Thanks to #Fresh for their quick response. Here is the complete solution to my problem:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
JS function to get the data from a web service:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
ret = response.d; // return response string object
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
Data structure outputted by the web service is:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7,095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1,137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220,429.41 }, ... ]
Data structure that is expected by JQPlot:
[ [ "2013-09-23T00:00:00", 7095.65 ] , [ "2013-08-22T00:00:00", 1137.96 ], [ "2013-07-24T00:00:00", 220429.41 ], ... ]
Note the removal of the comma's in the 'expected data' Bill field.
And finally, the function getElectricDataJSON() that is being called by btnASMX1 where 'chart2' is the ID of the div tags where the chart will be drawn.
function getElectricDataJSON() {
// Get JSON 'string' object
var ret = ajaxDataRenderer();
// If JSON string object is null, stop processing with friendly message
if (ret == null) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>CHARTS ARE NOT AVAILABLE AT THIS TIME</div>");
return false;
}
// Now push required data into a JSON array object
var sampleData = [], item;
$.each(ret, function (key, value) {
sampleData.push([value.todate, parseFloat(value.Bill.replace(/,/g, ""))]);
});
var plot = $.jqplot('chart2', [sampleData], {
title: 'AJAX JSON Data Renderer',
dataRenderer: sampleData,
...
});
}
The method signature for your datarender (i.e. ajaxDataRender) is wrong. The signature should look like this:
function(userData, plotObject, options) { ... return data; }
(See the documentation here)
In your example you are passing the datarenderer "ret" which is not a function with the correct datarender signature. Also the jsonurl you are passing to getElectricDataJSON() is redundant as at no point in your code is the data from "AccountsService.asmx/GetJSONData" persisted to "./jsondata.txt".
Hence you should change your code to this:
$(document).ready(function(){
function ajaxDataRenderer(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType: "json",
success: function (response) {
var ret = response;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var url = "AccountsService.asmx/GetJSONData";
function getElectricDataJSON() {
var plot1 = $.jqplot('chart2', url, {
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
});
}

Json MVC3 Object value in Javascript

I am sending json list from my controller:
public ActionResult LoadTree()
{
List<ListItem> list = new List<ListItem>() {
new ListItem() { Text = "Keyvan Nayyeri" },
new ListItem() { Text = "Simone Chiaretta" },
new ListItem() { Text = "Scott Guthrie" },
new ListItem() { Text = "Scott Hanselman" },
new ListItem() { Text = "Phil Haack" },
new ListItem() { Text = "Rob Conery" }
};
return new JsonResult { Data = list };
}
Trying to get the list in my view using:
var text =
$.ajax({
url: '/CourseCases/LoadTree',
dataType: 'json',
data: { },
cache: false,
type: 'GET',
success: function (data) {
}
});
alert(text);
I just get [object object]. How I can get the actual value of the object? Thanks in advance.
First you have to set the JsonRequestBehavior = JsonRequestBehavior.AllowGet in the JsonResult.
public ActionResult LoadTree()
{
List<ListItem> list = new List<ListItem>() {
new ListItem() { Text = "Keyvan Nayyeri" },
new ListItem() { Text = "Simone Chiaretta" },
new ListItem() { Text = "Scott Guthrie" },
new ListItem() { Text = "Scott Hanselman" },
new ListItem() { Text = "Phil Haack" },
new ListItem() { Text = "Rob Conery" }
};
return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
<script type="text/javascript">
$.ajax({
url: '/Home/LoadTree',
dataType: 'json',
data: {},
cache: false,
type: 'GET',
success: function (data) {
alert(data.length); // 6
// do whatever with the data
}
});
</script>
in success function you have to parse json to get actual data e.g.
var jsObject = JSON.parse(data);
and then access each item like jsObject.List[0].Text etc
Simple problem here. In your controller, you're actually assigning the list to a variable named Data inside the response data collection. Just because your success function takes a data parameter doesn't mean that the Data value you set in your controller automagically will become the data variable.
As your Data list is inside the data object: you need to do:
data.Data
inside your success function. Try this:
success: function(data) {
alert(data.Data.length);
}
function $.ajax() does not return value from server, so var text = $.ajax() will not work. You need to look at success handler instead
success: function (data) {
// data is the result of your ajax request
}
I strongly recommend you to read more at jQuery.Ajax
success(data, textStatus, jqXHR) A function to be
called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.

Categories