jqgrid - can I access server response with onSelectRow? - json

I get a JSON response from the server that I have full access to using loadComplete. Is it possible to be able to access the JSON response using
onSelectRow?
any other custom function defined outside of loadComplete?

You can define a variable which will hold the last state of the JSON response returned from the server:
var serverData;
$('#list').jqGrid({
datatype: 'json',
// ... other parameters
loadComplete: function (data) {
serverData = data; // or serverData = data.rows
// ...
},
onSelectRow: function (id) {
if (serverData) {
// here you can access serverData, but you need
// here probably find the item in the serverData
// which corresponds the id
}
}
});
If you have JSON data for example from the form
{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell": ["cell11", "cell12", "cell13"]},
{"id" :"2", "cell": ["cell21", "cell22", "cell23"]},
...
]
}
then you can save in serverData not the data directly. It could be interesting to save only cell part and save it as the value of the serverData[id]:
var serverData = [];
$('#list').jqGrid({
datatype: 'json',
// ... other parameters
loadComplete: function (data) {
var i, rows = data.rows, l = rows.length, item;
for (i = 0; i < l; i++) {
item = rows[i];
serverData[item.id] = item.cell;
}
// ...
},
onSelectRow: function (id) {
var item = serverData[id]; // the part of data which we need
}
});
If you use repeatitems: false setting in the jsonReader then you can save in the serverData only the part of the items (selected properties) which represented the row of the server data.
In any way you should save the part of the information from data parameter of loadComplete in some variable defined outside of the loadComplete.

Related

No Data in Google Data Studio

I'm trying to show JSON data got from API in Google Data Studio.
so I created community connector and in script verified JSON data from api.
here is script code.
function getFields(request) {
var cc = DataStudioApp.createCommunityConnector();
var fields = cc.getFields();
var types = cc.FieldType;
// var aggregations = cc.AggregationType;
fields.newDimension()
.setId('username')
.setType(types.TEXT);
fields.newMetric()
.setId('version')
.setType(types.NUMBER);
fields.newDimension()
.setId('address')
.setType(types.TEXT);
return fields;
}
function getSchema(request) {
var fields = getFields(request).build();
return { schema: fields };
}
function responseToRows(requestedFields, response) {
// Transform parsed data and filter for requested fields
var row = [];
requestedFields.asArray().forEach(function (field) {
switch (field.getId()) {
case 'username':
return row.push(response.result.user.createdByName);
case 'version':
return row.push(response.result.user.version);
case 'address':
return row.push(response.result.user.address);
default:
return row.push('');
}
});
return { values: row };
}
function getData(request) {
var requestedFieldIds = request.fields.map(function(field) {
return field.name;
});
var requestedFields = getFields().forIds(requestedFieldIds);
// Fetch and parse data from API
var options = {
'method' : 'post',
'contentType': 'application/json',
"headers":{ "api-key": request.configParams.api_key },
"payload": "{username:\""+username+"\", password: \""+password+"\"}",
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
var parsedResponse = JSON.parse(response);
var rows = responseToRows(requestedFields, parsedResponse);
console.log('getData request', parsedResponse);
return {
schema: requestedFields.build(),
rows: rows
};
}
this is JSON file
{
"result": {
"user": {
"type": "User",
"id": 1073787385,
"address": null,
"version": 1675247127459332096,
"createdBy": 310055,
"createdByName": "Jeirick Hiponia",
}
}
}
Result in data studio.
why don't address show?
And why no data? I think row.push in responseToRows() function is issue.
I'd like to show data like this.

Attempting to load list of values in column for Angular Table

I'm struggling with trying to figure out what I'm doing wrong, mostly down to not having a good understanding of AngularJS due to being new. The main goal is that I'm trying to list out all the values in the additionalText list out on the front-end, but it seems to be causing issue with this error:
Error: [$http:badreq] Http request configuration url must be a string or a $sce trusted object. Received: []
Context:
I have table in my application that relies on the API, this variable contains a list and outputs the following:
{
"name": "TEST",
"description": "TEST",
"additionalText": [
{
"name": "TEST",
"description": "TEST",
"lockId": 0
}
{
"name": "TEST",
"description": "TEST",
"lockId": 0
}
],
"lockId": 0
}
The API is working as expected, I can carry out all the necessary REST calls successfully. So I'm not struggling with that, the front-end is where I am having some difficulty.
HTML:
<td data-title="'additionalTexts'" sortable="'additionalTexts'">
<span ng-repeat="additionalText in additionalTextList[entity.name]">
<i>{{additionalText.name}}</i><br>
</span>
</td>
AngularJS:
$scope.refreshTextTable= function() {
SpringDataRestService.query(
{
collection: "APIURL"
},
function (response) {
var additionalTextRoles = response;
$scope.textTableOptions = new NgTableParams({}, {
dataset: additionalTextRoles,
counts: [],
});
// Also populate a list of all linked roles
for (var i = 0; i < additionalTextRoles.length; i++) {
var additionalTextRole = additionalTextRoles[i];
// This approach allows you to inject data into the callback
$http.get(additionalTextRole.additionalText).then((function (additionalTextRole) {
return function(response) {
$scope.additionalTextList[additionalTextRole.name] = response.additionalText;
};
})(additionalTextRole));
}
},
function (response) {
// TODO: Error Handling
}
);
};
Any help would be greatly appreciated, I'm really struggling with this one.
Can you try this below code:
$scope.refreshTextTable = function() {
SpringDataRestService.query({
collection: "APIURL"
},
function(response) {
var additionalTextRoles = response;
$scope.textTableOptions = new NgTableParams({}, {
dataset: additionalTextRoles,
counts: [],
});
// Also populate a list of all linked roles
for (var i = 0; i < additionalTextRoles.length; i++) {
var additionalTextRole = additionalTextRoles[i];
// This approach allows you to inject data into the callback
$http.get(additionalTextRole.additionalText).then((function(additionalTextRole) {
return function(response) {
$scope.additionalTextList = response.additionalText;
};
})(additionalTextRole));
}
},
function(response) {
// TODO: Error Handling
}
);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.3/angular.min.js"></script>
<td data-title="'additionalTexts'" sortable="'additionalTexts'">
<span ng-repeat="additionalText in additionalTextList">
<i>{{additionalText.name}}</i><br>
</span>
</td>
The error message says the url must be a string.
For debugging purposes, console.log the URL:
for (var i = 0; i < additionalTextRoles.length; i++) {
var additionalTextRole = additionalTextRoles[i];
// This approach allows you to inject data into the callback
var url = additionalTextRole.additionalText;
console.log(i, url);
$http.get(url).then((function (additionalTextRole) {
return function(response) {
$scope.additionalTextList[additionalTextRole.name] = response.additionalText;
};
})(additionalTextRole));
}
Also note that the response object returned by the $http service does not have a property named additionalText. So it is likely that the intention is response.data.additionalText. To avoid the IIFE, use the forEach method:
additionalTextRoles.forEach( role => {
var url = role.additionalText;
console.log(url);
$http.get(url).then((function(response) {
$scope.additionalTextList[role.name] = response.data.additionalText;
});
});

Parse JSON file containing multiple objects

I have a JSON file that contains multiple objects of the same structure that look like this:
{
"id": "123",
"type": "alpha"
}
{
"id": "321",
"type": "beta"
}
I'm using node.js to read the file.
fs.readFile(__dirname + "/filename.json", 'utf8', function(err, data) {
var content = JSON.parse(JSON.stringify(data));
If I do a console.log(content) things look good. I see the content of the json file. I'm trying to iterate over each object but I'm not sure how to do that. I've tried using
for(var doc in content)
but the doc isn't each object as I was expecting. How do I loop over the content to get each object in a json format so that I can parse it?
If content is an array, you can use
content.forEach(function (obj, index) { /* your code */ })
See documentation for Array.prototype.forEach()
if you need to just iterate, a forEach loop would work or a normal for loop :
for(var i = 0; i<content.length(); i++){
//perform whatever you need on the following object
var myobject = content[i];
}
Depend of the files, the two current answer (Osama and Daniel) assume you have a JSON Array:
[
{
"id": "123",
"type": "alpha"
},
{
"id": "456",
"type": "beta"
}
]
In which case, you can use any array iterator:
var async = require('async'),
content = require(__dirname + "/filename.json");
async.each(content, function (item, callback) {
//...
});
But in your case, it seems to not be JSON (no bracket to indicate array, and no comma to separate the objects), so in the case JSON.parse doesn t throw up any error, you'll need to isolate your objects first:
var fs = require('fs'),
async = require('async');
fs.readFile(__dirname + "/filename.notjson", 'utf8', function(err, data) {
var content = data.split('}');
async.map(content, function (item, callback) {
callback(null, JSON.parse(item));
}, function (err, content) {
console.log(content);
};
});

How to convert Backbone fetched object to proper Handlebars JSON Object?

Currently I have an issue with getting back a proper JSON object I'm fetching with Backbone fetch() and putting it into a Handlebars template.
See below my code, I have made a ugly workaround for now to test my Backend API
When converting to JSON with *.toJSON(), it just adds an extra object in-between and I don't need this extra object
Object [0]
--> books
----> Object [0]
------> Array of book
--------> book
--------> cities
JSON
{
"books": [
{
"book": 00001,
"cities": [
"TEST"
]
},
{
"book": 00002,
"cities": [
"TEST"
]
},
{
"book": 00003,
"cities": [
"TEST"
]
}
],
"more": true
}
JavaScript
var Book = Backbone.Model.extend({
default: {
book: 0,
cities: ["TEST1", "TEST2", "TEST3"]
},
url: function () {
return ".list.json";
}
});
var Books = Backbone.Collection.extend({
model: Book,
url: ".list.json"
});
var BooksView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render');
this.collection = new Books();
this.collection.fetch();
this.source = $('.e-books-template').html();
// Use an extern template
this.template = Handlebars.compile(this.source);
var self = this;
this.collection.fetch({
success: function () {
self.render();
},
error: function () {
console.log("ERROR IN BooksView");
}
});
},
render: function() {
var collect = JSON.stringify(this.collection);
collect = collect.slice(1, -1);
var html = this.template($.parseJSON(collect));
this.$el.html(html);
}
});
var booksView = new BooksView({ });
$(document).ready(function(){
booksView.$el = $('.e-books-content');
});
A Backbone collection expects an array of models but your JSON provides an object with the array under a books key. Parse the server response to format the data :
var Books = Backbone.Collection.extend({
model: Book,
url: ".list.json",
parse: function(data) {
return data.books;
}
});
Pass your data to your template via http://backbonejs.org/#Collection-toJSON ,
// directly as an array in your template
var html = this.template(this.collection.toJSON());
// under a books key
var html = this.template({
books: this.collection.toJSON()
});
And a demo http://jsfiddle.net/nikoshr/8jdb13jg/

How to create JSON object using jQuery

I have a JSON object in below format:
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
How can i create JSON object in jquery for above format. I want to create a dynamic JSON object.
Just put your data into an Object like this:
var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
myObject.pets = ["cat", "dog"];
Afterwards stringify it via:
var myString = JSON.stringify(myObject);
You don't need jQuery for this. It's pure JS.
A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.
If you want to convert your javascript object to a json string, use JSON.stringify(yourObject);
If you want to create a javascript object, simply do it like this :
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
I believe he is asking to write the new json to a directory. You will need some Javascript and PHP. So, to piggy back off the other answers:
script.js
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
var myString = 'newData='+JSON.stringify(yourObject); //converts json to string and prepends the POST variable name
$.ajax({
type: "POST",
url: "buildJson.php", //the name and location of your php file
data: myString, //add the converted json string to a document.
success: function() {alert('sucess');} //just to make sure it got to this point.
});
return false; //prevents the page from reloading. this helps if you want to bind this whole process to a click event.
buildJson.php
<?php
$file = "data.json"; //name and location of json file. if the file doesn't exist, it will be created with this name
$fh = fopen($file, 'a'); //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'.
$new_data = $_POST["newData"]; //put POST data from ajax request in a variable
fwrite($fh, $new_data); //write the data with fwrite
fclose($fh); //close the dile
?>
How to get append input field value as json like
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
Nested JSON object
var data = {
view:{
type: 'success', note:'Updated successfully',
},
};
You can parse this data.view.type and data.view.note
JSON Object and inside Array
var data = {
view: [
{type: 'success', note:'updated successfully'}
],
};
You can parse this data.view[0].type and data.view[0].note
var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({ url: 'test/set',
type: "POST",
data: model,
success: function (res) {
if (res != null) {
alert("done.");
}
},
error: function (res) {
}
});