Can you help me in this script? I am trying to pull data from list 'faq' and get an alert of output but without using CAML query. But i am not getting the output. Please help.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div id="divListItems"></div>
<script>
$(function () {
ExecuteOrDelayUntilScriptLoaded(addListItems, "sp.js");
});
function addListItems() {
var clientContext = new SP.ClientContext();
var oList = clientContext.get_web().get_lists().getByTitle('faq');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.getItem(itemCreateInfo);
clientContext.load(oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded() {
alert('Item created: ' + oListItem.get_item('Title'));
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
</script>
Please let me know if more details are required.
The best way to fetch SharePoint list item using REST API code is below.
ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");
function initializePage() {
var siteURL;
var itemsArray = [];
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function() {
var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
GetSampleListItems();
});
//Retrieve list items from sharepoint using API
function GetSampleListItems() {
siteURL = _spPageContextInfo.siteAbsoluteUrl;
console.log("from top nav - " + siteURL);
var apiPath = siteURL + "/_api/lists/getbytitle(''samplelist'')/items";
$.ajax({
url: apiPath,
headers: {
Accept: "application/json;odata=verbose"
},
async: false,
success: function(data) {
var items; // Data will have user object
var results;
if (data != null) {
items = data.d;
if (items != null) {
results = items.results
for (var i = 0; i < results.length; i++) {
itemsArray.push({
"Title": results[i].Title
});
}
}
}
},
eror: function(data) {
console.log("An error occurred. Please try again.");
}
});
}
}
With out REST API please find the below code.
var siteUrl = 'SiteCollection';//HEre you need to give your site collection URL
function retrieveAllListItems() {
var clientContext = new SP.ClientContext(siteUrl);//Will return current context
var oWebsite = clientContext.get_web();//Curent site
this.collList = oWebsite.get_lists();//Liist
clientContext.load(collList);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
//
function onQuerySucceeded() {
var listInfo = '';
//Below is the iteration for item
var listEnumerator = collList.getEnumerator();
while (listEnumerator.moveNext()) {
var oList = listEnumerator.get_current();
listInfo += 'Title: ' + oList.get_title() + ' Created: ' + oList.get_created().toString() + '\n';
}
alert(listInfo);
}
function onQueryFailed(sender, args)
//this will fire when you will any failure in your code..means in your Success method..
}
There are lots of good blog Plz find the below one
http://msdn.microsoft.com/en-us/library/hh185009%28v=office.14%29.aspx
If you are looking for anything else update me.
Related
Edit: code updated
I am trying to follow along with this blogpost which shows how to create a Suitelet which has a formatted table https://followingnetsuite.com/2020/10/16/skip-freemarker-by-delivering-saved-search-results-in-a-suitelet/
The blog post references adding a inline html field to hold the html mark up. I have tried to add this to the code though I know I am way off:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search", "N/ui/serverWidget"], function (search, ui) {
function onRequest(context) {
if (context.request.method === "GET") {
var form = ui.createForm({ title: "freemarker test" });
function getIssues() {
var issues = new Array();
var mySearch = search.load({
id: "customsearchcustomerallview",
});
var myPages = mySearch.runPaged({ pageSize: 1000 });
for (var i = 0; i < myPages.pageRanges.length; i++) {
var myPage = myPages.fetch({ index: i });
myPage.data.forEach(function (result) {
var issue = {};
mySearch.columns.forEach(function (col, index) {
issue["column_" + index] = {
label: col.label,
text: result.getText(col),
value: result.getValue(col),
};
});
issues.push(issue);
});
}
return issues;
}
function formatIssues(issues) {
var html = new Array();
html.push('<table class="RPT">');
html.push("<thead>");
if (issues.length > 0) {
var issue = issues[0];
html.push("<tr>");
for (var i = 0; i < 20; i++) {
if (issue.hasOwnProperty("column_" + i)) {
var sortType = isNaN(
issue["column_" + i].text || issue["column_" + i].value
)
? "string"
: "float";
html.push(
'<th data-sort="' +
sortType +
'">' +
issue["column_" + i].label +
"</th>"
);
}
}
html.push("</tr>");
}
html.push("</thead>");
html.push("<tbody>");
issues.forEach(function (issue) {
html.push("<tr>");
for (var i = 0; i < 20; i++) {
if (issue.hasOwnProperty("column_" + i)) {
var vAlign = isNaN(
issue["column_" + i].text || issue["column_" + i].value
)
? "left"
: "right";
html.push(
'<td align="' +
vAlign +
'">' +
(issue["column_" + i].text || issue["column_" + i].value) +
"</td>"
);
} else {
break;
}
}
html.push("</tr>");
});
html.push("</tbody>");
html.push("</table>");
return html.join("\n");
}
var htmlField = html.addField({
id: "custpage_html",
label: "html",
type: ui.FieldType.INLINEHTML,
});
htmlField.defaultValue = formatIssues(getIssues());
context.response.writePage(form);
}
}
return {
onRequest: onRequest,
};
});
I can't see the correct way to add this though. Where do I add the inline html field?
For a Suitelet, does the 'context.response.writePage(form)' need to be at the end of the rest of the code? (i.e. after the function that relates to the html markup?
Thanks
Add your HTML via the defaultValue property of the Inline HTML Field.
Structure your script as follows:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search", "N/ui/serverWidget"], function (search, ui) {
function onRequest(context) {
if (context.request.method === "GET") {
var form = ui.createForm({ title: "freemarker test" });
function getIssues() {
var issues = [];
return issues;
}
function formatIssues(issues) {
var html = [];
return html.join("\n");
}
var htmlField = form.addField({
id: "custpage_html",
label: "html",
type: ui.FieldType.INLINEHTML,
});
htmlField.defaultValue = formatIssues(getIssues());
context.response.writePage(form);
}
}
return {
onRequest: onRequest,
};
});
or, if you don't need any other NetSuite Form elements:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search"], function (search) {
function onRequest(context) {
if (context.request.method === "GET") {
function getIssues() {
var issues = [];
return issues;
}
function formatIssues(issues) {
var html = [];
return html.join("\n");
}
context.response.write(formatIssues(getIssues()));
}
}
return {
onRequest: onRequest,
};
});
You add the field to your form by calling Form.addField from your form object:
var field = html.addField({
id : 'custpage_inlineresults',
type : serverWidget.FieldType.INLINEHTML,
label : 'Search Results'
});
See SuiteAnswer #43669.
I am attempting to lock down a Suitelet that returns transactions with a search, but I cannot POST to it from a RESTlet unless it is available without login. It will return a page with a prompt to login if I set the Suitelet to be internal and call it from the RESTlet.
Is there a way to accomplish this without making the Suitelet available without login?
Example Suitelet (removed some irrelevant code to simplify):
define(['N/search', 'N/runtime'],
function(search, runtime) {
function onRequest(context) {
try {
var startDate = context.request.parameters.start_date;
var scriptObj = runtime.getCurrentScript();
if (!startDate) {
context.response.write('The start date is required in order to load the relevant records.');
return;
}
else {
log.debug('Start date parameter is: ' + startDate);
}
var searchCriteria = {
type: "invoice",
filters:
[
["datecreated","after", startDate],
"AND",
["mainline","is","T"]
],
columns:
[
search.createColumn({name: "tranid", label: "Document Number"}),
search.createColumn({name: "total", label: "Total"})
]
};
var searchObj = getAllResults(searchCriteria);
var searchResultCount = searchObj.length;
log.debug("searchObj result count", searchResultCount);
var invoices = [];
for (var i = 0; i < searchResultCount; i++) {
var tranId = searchObj[i].getValue({name: 'tranid'});
var total = searchObj[i].getValue({name: 'total'});
invoices.push({
tranId: tranId,
total: total
});
}
var jsonObj = {
success: 'true',
};
} catch (error) {
var jsonObj = {
success: 'false'
};
log.error('error', error);
return jsonObj;
}
log.debug('JSON obj', jsonObj);
context.response.write(JSON.stringify(jsonObj));
return jsonObj;
}
Example RESTlet:
define(['N/search','N/error','N/https','N/url','N/runtime'],
function(search, error, https, url, runtime) {
function doGet(request) {
log.audit({title:'request', details:request});
var startDate = request.startdate;
var params = {
'start_date': startDate,
'current_role': currentRole
};
var header = [];
header['Content-Type']='application/json';
try {
var suiteletURL = url.resolveScript({
scriptId: 'customscript_get_invoices',
deploymentId: 'customdeploy_get_invoices',
returnExternalUrl: true
});
log.debug('Suitelet URL', suiteletURL);
var formRequest = https.post({
url: suiteletURL,
body: params
});
return formRequest;
}
catch(e) {
var errorStr = 'Error posting to suitelet link';
log.error(errorStr, e.message);
throw error.create({
name: errorStr,
message: e.message,
notifyOff: true
});
}
}
return {
get: doGet
};
});
That will consume an extra concurrency vs moving the shared code into a library script file and calling it from both the Suitelet and the Restlet.
Wraparound web service calls in NetSuite should be avoided for that reason.
Thanks for looking into the code.
Here I am fetching some data using feed parser and taking out id's in navcodes array variable and wants to use these Id to make http call.Please find code below.
function processNavCode(){
var mfId = [53];
var preTitle = '';
var navCodes = [];
mfId.forEach(function(id){
var query = "http://portal.xyz.com/Rss.aspx?mf="+id;
feed(query, function(err, feeds) {
if (err) {
throw err;
}
feeds.forEach(function(feed){
var link = feed.link;
var title = feed.title;
var navCode = link.substr(link.length - 6);
if(title.split('-')[0].trim() != preTitle){
preTitle = title;
counter ++;
}
if(parseInt(navCode) != '')
navCodes.push = parseInt(navCode);
});
});
async.eachSeries(navCodes,insertbulkMFValues,function(){
console.log('I am done');
});
// insertbulkMFValues(navCode);
//Directly call insertbulkMFValues function
});
}
I have also tried to call the insertbulkMFValues directly as commented now but due to async nature of nodejs, I am getting the error of either 'Socket hang up' or 'read ECONNRESET'. I checked and used async but not able to work with that also.
var insertbulkMFValues =function(navCode,callback){
var options = {
host: 'www.quandl.com',
path: '/api/v3/datasets/AMFI/'+navCode+'.json?api_key=123456789&start_date=2013-08-30',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
var req1 = https.request(options, function(response) {
var body = '';
response.setEncoding('utf8');
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
if(typeof body === "string") {
var json = JSON.parse(body);
}
var mfData = json.dataset.data;
var schemeId = json.dataset.dataset_code;
var schemeName = json.dataset.name;
var isinCode = json.dataset.description;
var valueData=[];
for (var k = 0; k < mfData.length; k++) {
var myDate = new Date(mfData[k][0]);
valueData.push({
date:myDate,
NAV:parseFloat(mfData[k][1]).toFixed(2)
});
}
var query = { "navCode": schemeId };
var newData = {
createdDate: Date.now(),
navCode: schemeId,
schemeCode:count,
schemeName:schemeName,
ISINCode:isinCode,
values:valueData
};
MHistory.findOneAndUpdate(query, newData , {upsert:true}, function(err, doc){
if(err)
console.log('Errorr');
else
console.log('Success');
});
});
});
req1.on('error', function(e) {
console.log('problem with request: ' + e.message);
callback(true);
});
req1.end();
}
Thanks in advance..
J
You can directly call insertbulkMFValues for each navCode like:
if(parseInt(navCode) != '') {
insertbulkMFValues(navCode, function () {
console.log('something'}
});
}
Anything that you intend to do must be within the callback of the asynchronous function.
One option for you is to use the waterfall or parallel method of the async library to retrieve all feeds for each id and then invoke
async.eachSeries(navCodesAccumulated,insertbulkMFValues,function(){
console.log('I am done');
});
within the final result callback using the codes obtained.
I am trying to read in a large file, do some computation and then write to a much bigger file. To prevent excessive memory consumption, I am using streams. The problem that I am facing is that the writestream is not firing the "drain" event, which signals that the writes have been flushed to disk. In order to prevent "back-pressure", I am waiting for the drain event to be fired before I start writing to the buffer again. While debugging I found that after a .write() call returns false and the line fvfileStream.once('drain', test) is executed, the program just stops and does not do anything.
Here is the code:
var fs = require('fs');
//a test function I created to see if the callback is called after drain.
var test = function(){
console.log("Done Draining");
}
fs.readFile('/another/file/to/be/read', {
encoding: "utf8"
}, function(err, data) {
if (err) throw err;
//Make an array containing tags.
var tags = data.split('\n');
//create a write stream.
var fvfileStream = fs.createWriteStream('/path/TagFeatureVectors.csv');
//read in the question posts
var qfileStream = fs.createReadStream('/Big/file/QuestionsWithTags.csv', {
encoding: "utf8"
});
var partialRow = null;
var writable = true;
var count = 0;
var doRead = function() {
var qData = qfileStream.read();
var questions = qData.split('\n');
if (partialRow != null) {
questions[0] = partialRow + questions[0];
partialRow = null;
}
var lastRow = questions[questions.length - 1];
if (lastRow.charAt(lastRow.length - 1) != '\n') {
partialRow = lastRow;
}
questions.forEach(function(row, index, array) {
count++;
var fields = row.split(',');
console.log("Processing question number: " + count + " id: " + fields[0]);
var tagString = fields[1];
var regex = new RegExp(/<([^>]+)>/g);
tags.forEach(function(tag, index, array) {
var found = false;
var questionTags;
while ((questionTags = regex.exec(tagString)) != null) {
var currentTag = questionTags[1]
if (currentTag === tag) {
found = true;
break;
}
};
//This is where the writestream is written to
if (found) {
writable = fvfileStream.write("1,", "utf8");
}else {
writable = fvfileStream.write("0,","utf8");
}
});
});
fvfileStream.write("\n");
}
qfileStream.on('readable', function() {
if (writable) {
doRead();
} else {
//Waiting for drain event.
fvfileStream.once('drain', test);
}
});
qfileStream.on('end', function() {
fvfileStream.end();
});
});
Updated
Based on advise provided by #loganfsmyth, I implemented transform streams, but still ran into the same issue. Here is my updated code:
var fs = require('fs');
var stream = require('stream');
var util = require('util');
var Transform = stream.Transform;
function FVCreator(options) {
// allow use without new
if (!(this instanceof FVCreator)) {
return new FVCreator(options);
}
// init Transform
Transform.call(this, options);
}
util.inherits(FVCreator, Transform);
var partialRow = null;
var count = 0;
var tags;
FVCreator.prototype._transform = function(chunk, enc, cb) {
var that = this;
var questions = chunk.toString().split('\n');
if (partialRow != null) {
questions[0] = partialRow + questions[0];
partialRow = null;
}
var lastRow = questions[questions.length - 1];
if (lastRow.charAt(lastRow.length - 1) != '\n') {
partialRow = lastRow;
questions.splice(questions.length - 1, 1);
}
questions.forEach(function(row, index, array) {
count++;
var fields = row.split(',');
console.log("Processing question number: " + count + " id: " + fields[0]);
var tagString = fields[1];
var regex = new RegExp(/<([^>]+)>/g);
tags.forEach(function(tag, index, array) {
var found = false;
var questionTags;
while ((questionTags = regex.exec(tagString)) != null) {
var currentTag = questionTags[1]
if (currentTag === tag) {
found = true;
break;
}
};
if (found) {
that.push("1,", "utf8");
} else {
that.push("0,", "utf8");
}
});
});
this.push("\n", "utf8");
cb();
};
fs.readFile('/another/file/to/be/read', {
encoding: "utf8"
}, function(err, data) {
if (err) throw err;
//Make an array containing tags.
tags = data.split('\n');
//write to a file.
var fvfileStream = fs.createWriteStream('/path/TagFeatureVectors.csv');
//read in the question posts
var qfileStream = fs.createReadStream('/large/file/to/be/read', {
encoding: "utf8"
});
var fvc = new FVCreator();
qfileStream.pipe(fvc).pipe(fvfileStream);
});
I am running this on OSX Yosemite.
Using Parse.com for few months now, I started to create some Cloud Function To let me create and retrieve some element in a TimeLine
I need to get my information from timeline's class and once I retrieve elements, I have to call getStat to add in the same object Widgets both information from my query and from the results from getStat.
I have tried to use Promise to achieve this, but not sure it was the best way to deal with it. Any suggestions / help ?
Parse.Cloud.define("getTimeline", function(request, response) {
var user = request.params.user;
var limit = request.params.limit;
var page = request.params.page;
if (limit === undefined) limit = 10;
if (page === undefined) page = 0;
var Timeline = Parse.Object.extend("timeline");
var query = new Parse.Query(Timeline);
query.equalTo("user", user);
query.descending('createdAt');
query.limit(limit);
query.skip(page * limit);
var Widgets = {};
query.find().then(function(results) {
var promise = Parse.Promise.as();
_.each(results, function(result) {
var Widget = new Object();
Widget.data = result;
var timeline_id = result.get('timeline_id');
promise = promise.then(function() {
return Parse.Cloud.run('getStats', {
'timeline_id': timeline_id
}).then(function(stat) {
Widget.stat = stat;
Widgets[timeline_id] = Widget;
});
});
});
return promise;
}).then(function() {
response.success(Widgets);
},
function(error) {
response.error("Error: " + error.code + " " + error.message);
});
});