Uncaught TypeError: Cannot read property 'setRowData' of undefined - javascript

I am using with Angular 1.x with ag-grid. first of all I am confused how I do activate enterprise feature. I am evaluating now we are planing to buy the enterprise but support is pretty weak.
Now the actual problem I am trying to feed the data from ElasticSearch to the grid. I am trying to simulate like demo of ag-grid. If change the pagesize it will retrieve the data from ES server and feed the grid with new datasets with new pagesize. For that I am using $scope.gridOptions.api.setRowData(data) on any action if I try to update the grid I mean setRowData. I am getting error "method is undefined" It works for the first time when it loads the page.
How do I resolve this issue? Am I missing anything?
Function: This is the function where I invoking the $scope.gridOptions.api.setRowData(data) and I am getting error
"Uncaught TypeError: Cannot read property 'setRowData' of undefined"
function displayGrid(fromDate, toDate, fieldNameArray, affiliate, product,consmb, region, customer, page, pageSize)
{
// Constructing Query from dashboard input
var gridQuery = globalFiltersDrillDown(fromDate, toDate, fieldNameArray, page, pageSize);
var finalGridQuery = buildQueryForDrillQuery(affiliate,product, consmb, region, customer, gridQuery, "" , false);
console.log("final Query :" + JSON.stringify(finalGridQuery));
var data =[];
setTimeout(function ()
{
esClientIndirect.search
(
{
index: esIndex1,
type: esType1,
size : pageSize,
from : page,
body: finalGridQuery
},
function (error, response, status)
{
$scope.numberOfRecords = numberCommas(response.hits.total);
if(error)
{
$scope.error = "Error : " + status ;
}
else
{
var startBrace = "{ ";
var endBrace = " }"
data.length = 0;
var k = 0;
for(var o in response.hits.hits)
{
var dataFields = response.hits.hits[o].fields;
var numberOfElements = fieldNameArray.length -1;
var row = startBrace;
for (var i in dataFields)
{
var columnName = fieldNameArray[k];
var columnValue = dataFields[columnName];
if (k == numberOfElements)
{
row += (" \"" + columnName +"\" : \"" + columnValue +"\"");
}
else
{
row += (" \"" + columnName +"\" : \"" + columnValue +"\",");
}
k = k+1;
}
row += endBrace;
k =0;
data.push(JSON.parse(row));
}
// pushing data into the ag-grid
setTimeout(function()
{
$scope.gridOptions.api.setRowData(data);
}, 200);
}
}, 100); // end of elastic search call back
}); // end of elastic search set time out call back

The error indicates that the api doesn't exist. Have you made sure that you have instantiated $scope.gridOptions before you do this call?

Related

How to render multiple html lists with AppScrip?

I am new to the world of * AppScript * I am currently designing a ** WepApp ** which is made up of html lists that connect to Mysql, when I individually test my lists paint correctly and their icons modify and update the data, without However ** the problem is ** when I join all my lists and call them through their corresponding url only the last one paints me the others are blank. For example of 10 lists I call # 2 the log tells me to call 10; I call 5 the same thing happens and if I call 10 it paints the data and they are allowed to be modified.
Within what I have searched I find that my problem lies in the way I render my pages but I cannot find the right path, so I ask for your support.
function doGet(e) {
var template ;
var view = e.parameters.v;
if(view == null){
template = HtmlService.createTemplateFromFile("Index");
}if(view == "Index"){
template = HtmlService.createTemplateFromFile("Index");
}if(view != null && view != "Index"){
template = HtmlService.createTemplateFromFile(view);
}
return template.evaluate()
.setTitle('Documental')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getTemplate(view){
return HtmlService.createTemplateFromFile(view);
}
and with this JavaScript method I connect my appscript code to pass it to my html
window.onload = function () {
google.script.run
.withSuccessHandler(run_This_On_Success)
.withFailureHandler(onFailure)
.readAreaPRE();
};
function onFailure(error) {
var div = document.getElementById("output");
div.innerHTML = "ERROR: " + error.message;
}
function run_This_On_Success (readAreaPRE) {
let table = $("#selectTable");
table.find("tbody tr").remove();
table.append("<tr><td>" + "</td><td>" + "</td></tr>");
readAreaPRE.forEach(function (e1, readAreaPRE) {
table.append(
"<tr><td>" +
e1[0] +
"</td><td>" +
e1[1] +
"</td><td>" +
"<p><a class='modal-trigger' id=" + e1[0] + " href='#modal1' onclick='capturaid("+e1[0]+",'"+ e1[1]+"')'><i class='material-icons'>edit</i></a>" +
"<a class='modal-trigger' href='#modal3' onclick='capturaidsup("+e1[0]+")'><i class='material-icons'>delete</i></a></p>" +
"</td></tr>"
);
});
};
function capturaidsup(dato1){
$("#delAreaPRE").val(dato1)
}
function capturaid(item1,item2) {
$("#uptAreaPRE1").val(item1);
$("#uptAreaPRE2").val(item2);
}
here is my function: readArePRE
function readAreaPRE() {
var conn = Jdbc.getCloudSqlConnection(url, user, contra);
var stmt = conn.createStatement();
stmt.setMaxRows(1000);
var results = stmt.executeQuery(
"CALL `BD_CENDOC_COL`.`sp_lee_tb_ref_AreasPRE`()"
);
var numCols = results.getMetaData().getColumnCount();
var rowString = new Array(results.length);
var i = 0;
while (results.next()) {
var id_areaPRE = results.getInt("id_areaPRE");
var AreaPRE = results.getString("AreaPRE");
rowString[i] = new Array(numCols);
rowString[i][0] = id_areaPRE;
rowString[i][1] = AreaPRE;
i++;
}
return rowString;
conn.close();
results.close();
}
Thank you in advance, any correction to ask my question will be welcome.

Query Parent and child data in one call - parse.com + javascript

I am trying to understand how to query related classes in one call from parse.com using javascript.
I have 2 classes Post and Comment. Post has a column of type relation named 'Comment' and Comment has a column 'parent' of type pointer.
I use the following following code based on parse docs, to save a post and related comment
var Post = Parse.Object.extend("Post");
var Comment = Parse.Object.extend("Comment");
//Create the post
var myPost = new Post();
myPost.set("title", "I'm Hungry");
myPost.set("content", "Where should we go for lunch?");
// Create the comment
var myComment = new Comment();
myComment.set("text", "Let's do subway.");
myComment.set("parent", myPost);
myComment.save();
I am trying to query data like this
var query = new Parse.Query("Post");
query.descending("createdAt");
query.find({
success: function(results) {
for(var i = 0; i < results.length; i++) {
var post = results[i];
var relation = post.relation('Comment');
relation.query().find({
success: function(comments) {
for(var j = 0; j < comments.length; j++) {
console.log(comments[j].get("content"));
}
}
});
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
Can anybody tell me what i am doing wrong here?
The problem in your code is that you're not setting up the relation between the post and the comment. Without that relation setup your query won't work. Here's the working code. Note that I have to save the comments before creating the relation, otherwise you'll get an error from parse.
function createPost() {
var Post = Parse.Object.extend("Post");
var Comment = Parse.Object.extend("Comment");
//Create the post
var myPost = new Post();
myPost.set("title", "I'm Hungry");
myPost.set("content", "Where should we go for lunch?");
// Create the comment
var comment1 = new Comment();
comment1.set("text", "Let's do subway.");
comment1.set("parent", myPost);
var comment2 = new Comment();
comment2.set("text", "Let's do Hoagies.");
comment2.set("parent", myPost);
return Parse.Object.saveAll([comment1, comment2]).then(function() {
// Set the relationship
var relation = myPost.relation('comments');
relation.add(comment1);
relation.add(comment2);
return myPost.save();
});
}
createPost().then(function() {
var query = new Parse.Query("Post");
query.descending("createdAt");
var posts = [];
return query.find().then(function(results) {
var promises = [];
for(var i = 0; i < results.length; i++) {
var post = results[i];
var relation = post.relation('comments');
var postData = { post : post, comments : [] };
posts.push(postData);
console.log("Post : " + post.get('title'));
promises.push(relation.query().find({
success: function(comments) {
for(var j = 0; j < comments.length; j++) {
console.log("Comment " + j + " : " + comments[j].get("text"));
postData.comments.push(comments[j]);
}
}
}));
}
return Parse.Promise.when(promises);
},
function(error) {
alert("Error: " + error.code + " " + error.message);
}
).then(function() {
console.log(posts);
return posts;
});
})

Changing the objectId thats returned in a query to that of the actual user

Using parse.com and JavaScript SDK.
This is what I'm attempting to achieve.
A list of users (friends) is returned on the page to the user, They can then click on one of these users and the page is updated to list all of that users items (which are basically images).
This query works correctly and returns a list of users.
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var query = new Parse.Query(FriendRequest);
query.include('toUser');
query.include('SentTo');
query.include("myBadge");
query.equalTo("fromUser", currentUser);
query.equalTo("status", "Request sent");
query.find({
success: function (results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('toUser').get('pic'),
friendRequestId: results[i].id,
username: results[i].get('toUser').get('username')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function (item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div class="wrapper" data-friend-request-id="' + item.friendRequestId + '"></div>');
wrapper.append('<img class="images" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.username + '</div>');
$('#container').append(wrapper);
});
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
****This below query should contain the user who has selected above and stored in window.selectedFriendRequestId (which is saved in the variable friendRequest ****
This query looks at the myBadges class and the user reference "SentTo" the ref used is for example a3aePaphBF which is the actual _User objectID.
function FriendProfile() {
var friendRequest = "window.selectedFriendRequestId";
console.log(window.selectedFriendRequestId);
var myBadges = Parse.Object.extend("myBadges");
var query = new Parse.Query(myBadges);
query.equalTo("SentTo", friendRequest);
query.find({
success: function (results) {
// If the query is successful, store each image URL in an array of image URL's
imageURLs = [];
for (var i = 0; i < results.length; i++) {
var object = results[i];
imageURLs.push(object.get('BadgeName'));
}
// If the imageURLs array has items in it, set the src of an IMG element to the first URL in the array
for (var j = 0; j < imageURLs.length; j++) {
$('#imgs').append("<img src='" + imageURLs[j] + "'/>");
}
},
error: function (error) {
// If the query is unsuccessful, report any errors
alert("Error: " + error.code + " " + error.message);
}
});
}
The issue is that the first query is not returning an objectId that I can use in the second query as a reference. For example a3aePaphBF is not returned but cr3LG70vrF is.
How to I return the actual _User objectid in the first query so I can make these match?
To get the ID of a user:
results[i].get('toUser').id
So if you update your section of code that is doing friends.push(...):
friends.push({
imageURL: results[i].get('toUser').get('pic'),
friendRequestId: results[i].id,
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id
});
Then in your bit where you create the wrapper:
_.each(friends, function (item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div class="wrapper"'
+ ' data-friend-request-id="' + item.friendRequestId + '"'
+ ' data-to-user-id="' + item.userId + '"></div>');
wrapper.append('<img class="images" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.username + '</div>');
$('#container').append(wrapper);
});
Notice that I've added another data-property to hold the ID of the toUser.
Now if you followed the tips from your other question, you can tweak the code that attaches the on-click handler to pass toUserId also:
$('#container').on('click', '.wrapper', function () {
var wrapper = $(this);
var friendRequestId = wrapper.data('friendRequestId');
var toUserId = wrapper.data('toUserId');
FriendProfile(friendRequestId, toUserId);
// other code ...
});
Lastly your FriendProfile() function can now use either of those parameters as needed:
function FriendProfile(friendRequestId, toUserId) {
var toUser = new Parse.User();
toUser.id = toUserId;
var myBadges = Parse.Object.extend("myBadges");
var query = new Parse.Query(myBadges);
query.equalTo("SentTo", toUser);
// ... etc ...
}
NOTE: The User class should be locked down for privacy reasons, you shouldn't be able to read any properties of other users except in Cloud Code when you have the following line in your Cloud Function:
Parse.Cloud.useMasterKey();

Javascript How to SetTimeOut while getting a list of files with Scripting.FileSystemObject

This code is for internal, offline, single user use, IE only. The code looks at a folder, and lists all files including those in subfolders. It sorts through the data based on some date fields and datelastmodified. It also uses and if to throw out thumbs.db entries. All of the data is put into a table.
My issue is that this script can take a long time to get the data. I would like to add a progress bar but the progress bar cant update while the script is running. After some research it looks like SetTimeOut can allow the page elements to be updated as the script runs, therefore allowing the progress bar to work and looking overall cleaner. However I can not figure out of to implement SetTimeOut into my existing code.
<script type="text/javascript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
function ShowFolderFileList(folderspec) {
var beginningdate = new Date(startdate.value);
var finishdate = new Date(enddate.value);
var s = "";
var f = fso.GetFolder(folderspec);
var subfolders = new Enumerator(f.SubFolders);
for (subfolders.moveFirst(); !subfolders.atEnd(); subfolders.moveNext()) {
s += ShowFolderFileList(subfolders.item().path);
}
// display all file path names.
var fc = new Enumerator(f.files);
for (i = 0; !fc.atEnd(); fc.moveNext()) {
if (fc.item().name != "Thumbs.db") {
var dateModified = fc.item().DatelastModified;
if (dateModified >= beginningdate && dateModified <= finishdate) {
Date.prototype.toDateString = function () {
return [this.getMonth() + 1, '/', this.getDate(), '/', this.getFullYear()].join('');
}
var dateModifiedClean = (new Date(fc.item().DatelastModified).toDateString());
s += "<table border=0 width=100% cellspacing=0><tr " + ((i % 2) ? "" : "bgcolor=#EBF1DE") + "><td width=75%><font class=find><b>" + fc.item().ParentFolder.name + "</b>" + " - " + fc.item().name + "</font></td><td width=25% align=right><font class=find>" + dateModifiedClean + "</font></td></tr>";
i++;
}
}
}
var results = s + "</table>";
return results;
}
function listFiles() {
outPut.innerHTML = ShowFolderFileList('*Path to scan*');
}
</script>
outPut is the ID of a div tag where the results table is displayed. A button calls the listfiles function.

Passing Javascript variable from one function to another function for use in a sqlite query

I am trying to write a Javascript function that obtains an array of unique ids from an sqlite database & then passes them to be used in another function where the ids can be used in another sql query, they also form part of a dynamically created list.
I have managed to pass the ids row['id'] to the array variable window.symp[i]. But I have not been able to access them correctly in the second function below, the second function correctly uses the ids to create the dynamic html but the variable passed to the sqlite query either fails or is the same value in all the list items created. Any help would be greatly appreciated - I have included both functions below:
function showContent() {
db.transaction(function (tx) {
tx.executeSql("SELECT id, notes FROM webkit WHERE notes LIKE 'A%'", [], function (tx, result) {
var notesanode = document.getElementById('notesa');
notesanode.innerHTML = "";
for (var i = 0; i < result.rows.length; ++i) {
var row = result.rows.item(i);
window.symp[i] = i;
window.symp[i] = row['id'];
var noteadiv = document.createElement('div');
noteadiv.innerHTML = '<li class=\"arrow\"><a id=\"0\" onClick=\"showSymptoms()\" href=\"#symptoms\">' + row['notes'] + " " + row['id'] + '</a></li>';
notesanode.appendChild(noteadiv);
}
}, function (tx, error) {
alert('Failed to retrieve notes from database - ' + error.message);
return;
});
});
}
function showSymptoms() {
db.transaction(function (tx) {
tx.executeSql("SELECT sid, symptom FROM slinks WHERE id LIKE ('" + symp + "')", [], function (tx, result) {
var symptomnode = document.getElementById('symptomid');
symptomnode.innerHTML = "";
for (var i = 0; i < result.rows.length; ++i) {
var row = result.rows.item(i);
var symptomdiv = document.createElement('div');
symptomdiv.innerHTML = '<p><label> <input type=checkbox>' + row['symptom'] + '</label></p>';
symptomnode.appendChild(symptomdiv);
}
}, function (tx, error) {
alert('Failed to retrieve notes from database - ' + error.message);
return;
});
});
}
I see two things:
The main issue is that you need
"SELECT sid, symptom FROM slinks WHERE id LIKE ('" + window.symp.join(',') + "')"
instead of what you have up there.
The second issue is that you have
window.symp[i] = i;
window.symp[i] = row['id'];
you can just go ahead and remove window.symp[i] = i; because it gets immediately overwritten by the line that follows it.

Categories

Resources