printing all records using only one alert - javascript

I have the following code with the JSFiddle for the same here:
var result = [
{"Id": 10004, "PageName": "club"},
{"Id": 10040, "PageName": "qaz"},
{"Id": 10059, "PageName": "jjjjjjj"}
];
$.each(result, function(i, item) {
alert(result[i].PageName);
});
In order to see all the results, I have to click Ok in alert window two times. How can I display the contents using one alert only?
//f1.js ---
var PatientReviewPage = (function () {
var cls = function () { }
var self = cls.prototype;
self.urlKey = "showmrn";
self.getData = function (mrn_) {
/*
if (isEmpty(mrn_)) { alert("Invalid mrn in getData()"); return false; }
// Lookup the AJAX web service URL
var url = regman.getWebServiceURL(self.urlKey);
if (isEmpty(url)) { alert("Invalid URL in getData()"); return false; }
var ajaxRequest = jQuery.ajax({
//beforeSend: TODO: show spinner!
data: {
registry_id: regman.registry.id,
mrn: mrn_
},
dataType: "json",
method: "GET",
url: url
})*/
//Some code related to ajax reques
this.done(function (data_, textStatus_, jqXHR_) {
// Validate the web service and retrieve the status.
if (typeof (data_) === "undefined" || data_ === null) {
alert("Invalid data returned from web service");
return false;
}
if (isEmpty(data_.webservice_status) || isEmpty(data_.webservice_status.status)) {
alert("Invalid web service status");
return false;
}
if (data_.webservice_status.status != "SUCCESS") {
alert(data_.webservice_status.message);
return false;
}
self.processdataDocuments(data_.data_document_list);
});
this.fail(function (jqXHR_, textStatus_, errorThrown_) {
alert("Error in getData(): " + errorThrown_);
return false;
});
};
// Initialize the page
self.initialize = function () {
var mrn = regman.selectedData["mrn"];
if (isEmpty(mrn)) {
alert("Invalid MRN provided by calling page");
return false;
}
self.getData(mrn);
};
self.processdataDocuments = function (collection_) {
if (isEmpty(collection_) || collection_.length < 1) {
// Populate the count and exit
jQuery("#nlpDocumentCount").html("(0)");
return true;
}
var source =
{
localdata: collection_,
datatype: "array"
};
var dataAdapter = new $.jqx.dataAdapter(source, {
loadComplete: function (data) { },
loadError: function (xhr, status, error) { }
});
$("#nlpDocumentPanel").jqxGrid(
{
source: dataAdapter,
width: '1000',
height: 150,
columns: [
{
text: 'Type', datafield: 'nc_type'
},
{
text: 'SubType', datafield: 'nc_subtype'
},
{
text: 'Concept', datafield: 'concept_text'
},
{
text: 'Date', datafield: 'nc_dos'
}
]
});
// For getting the contents of a row, I am using jqxgrid approach as mentioned in their doc here :
// http://www.jqwidgets.com/getting-the-clicked-grid-row/
$("#nlpDocumentPanel").on('rowclick', function (event) {
var row = event.args.rowindex;
var datarow = $("#nlpDocumentPanel").jqxGrid('getrowdata', row);
response = JSON.stringify(datarow, null, 10)
//alert(jsonStringify); // This alert displays the JSON data in a formatted manner
var obj = jQuery.parseJSON(response);
//alert("display Subtype "+obj.nc_subtype) // Works fine
self.mySubtype = obj.nc_subtype;
});
};
//I added this line for the demo to show 'f2' accessing this property from 'f1'. You should remove it if copying this code into your application
self.mySubtype = "Foo";
return cls;
})();
var f1 = new PatientReviewPage();
//f2.js ---
var DocumentDetailsDialog = (function () {
var cls = function () { }
var self = cls.prototype;
alert(f1.mySubtype);
/*this.getData = function (IDNumber_) {
// some code will be here
var ajaxRequest = jQuery.ajax({
// some code will be here
})
.done(function (data_, textStatus_, jqXHR_) {
// some code will be here
})
.fail(function (jqXHR_, textStatus_, errorThrown_) {
// some code will be here
});
};*/
return cls;
})();
var f2 = new DocumentDetailsDialog();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can use map() and join() and return string with page names.
var result = [
{"Id": 10004, "PageName": "club"},
{"Id": 10040, "PageName": "qaz"},
{"Id": 10059, "PageName": "jjjjjjj"}
];
var r = result.map(function(e) {
return e.PageName;
}).join(' ');
alert(r);

Build a string with the results and alert the string:
alert(result.map( _ => _.PageName).join(', '))

Related

In jquery after finish of first loop call some other function

In a $.each function I am calling jquery ajax method which is returning a list, so that returned list I want to use in other function and parallel that jquery ajax loop will also work and return the value continuously and call that other function, but it's not happening parallel,means after completing of $.each function it's calling the other function with the last returned list. But I want once its returned list call the other function with that returned value and like this continue.
function Test() {
var x = $('#myHiddenVar').val();
$.each($.parseJSON(x), function (key, value) {
$.ajax({
type: 'POST',
url: '#Url.Action("GeoIPDashboardDataload", "Home")',
data: { branchId: value },
async: false,
error: function (xhr, status, error) {
console.log(error);
},
success: function (data) {
debugger;
if (data != null) {
$(data.logs).each(function (index) {
debugger;
var _id = index;
var _logId = data.logs[index].id;
var _dstIP = data.logs[index].dst_ip;
var _dstCountryName = data.logs[index].dst_geoData.country_name;
var _dstlatitude = data.logs[index].dst_geoData.latitude;
var _dstlongitude = data.logs[index].dst_geoData.longitude;
var _srcIP = data.logs[index].src_ip;
var _srcCountryName = data.logs[index].src_geoData.country_name;
var _srclatitude = data.logs[index].src_geoData.latitude;
var _srclongitude = data.logs[index].src_geoData.longitude;
var _threatType = data.logs[index].threat_type;
var locations = {
"id": _id,
"logId": _logId,
"dstIP": _dstIP,
"dstCountryName": _dstCountryName,
"dstlatitude": _dstlatitude,
"dstlongitude": _dstlongitude,
"srcIP": _srcIP,
"srcCountryName": _srcCountryName,
"srclatitude": _srclatitude,
"srclongitude": _srclongitude,
"threatType":_threatType
};
queryStr = { "locations": locations };
queryArr.push(queryStr);
});
companyName = data.comp;
branchName = data.branch;
attacks.init();
}
}
});
});
}
------------
attacks = {
interval: getRandomInt(attack_min, attack_max),
init: function () {
setTimeout(
jQuery.proxy(this.getData, this),
this.interval
);
},
getData: function () {
var srclat = arr[arrayCount].src_geoData.latitude;
var srclong = arr[arrayCount].src_geoData.longitude;
var dstlat = arr[arrayCount].dst_geoData.latitude;
var dstlong = arr[arrayCount].dst_geoData.longitude;
var sourceip = arr[arrayCount].src_ip;
var attackerIP = arr[arrayCount].dst_ip;
var srccountry = arr[arrayCount].src_geoData.country_name;
attackdiv_slatlong = arr[arrayCount].dst_geoData.country_name;
hits.push({
origin: { latitude: srclat, longitude: srclong },
destination: { latitude: dstlat, longitude: dstlong }
});
map.arc(hits, { strokeWidth: 2 });
boom.push({
radius: 7, latitude: dstlat, longitude: dstlong,
attk: attackerIP
});
map.bubbles(boom, {
popupTemplate: function (geo, data) {
return '<div class="hoverinfo">' + data.attk +'</div>';
}
});
arrayCount++;
this.interval = getRandomInt(attack_min, attack_max);
this.init();
},
};
So the above test method calling from document.ready function and after pushing all item into the queryArr array call attack.init and inside attack.int i am using that array list.

Customizing easyAutoComplete

var options = {
url: function (phrase) {
return "location/autoComplete?key=" + phrase;
},
getValue: "cityName",
template: {
type: "custom",
method: function (value, item) {
return value + ", " + item.stateName;
}
},
list: {
onClickEvent: function () {
var selectedLongitude = $("#autoCompleteSearch").getSelectedItemData().longitude;
var selectedLatitude = $("#autoCompleteSearch").getSelectedItemData().latitude;
userPos = {
lat: Number(selectedLatitude),
lng: Number(selectedLongitude)
};
map.setCenter(userPos);
map.setZoom(17)
},
showAnimation: {
type: "fade", //normal|slide|fade
time: 400,
callback: function () {
}
},
hideAnimation: {
type: "slide", //normal|slide|fade
time: 400,
callback: function () {
}
}
}
};
This is the code I am using right now to fetch a remote webservice data. Now I need to get the data and remove the duplicate "city names". Also I need to show "Data not available" or some custom method when there is no data from the webservice. I am kind of stuck. Would be great if someone could point me on how to achieve this.
You can get rid of duplicates using a helper function:
function removeDuplicates(input) {
if (!input) { //Falsy input
return input;
}
var isArray = Array.isArray(input) ? [] : {};
var items = [];
var output = {};
for (var key in input) {
if (items.indexOf(input[key]) < 0) {
items.push(input[key]);
if (!isArray) {
output[key] = input[key];
}
}
}
return isArray ? items : output;
}
You can show your custom text if Array.isArray(input) ? (input.length === 0) : (Object.keys(input).length === 0 && input.constructor === Object).

Custom Contexmenu for different node in jstree angular directive

In my project I have tree based on jstee angular directive. I build this tree with help 2 api requests. This requests provide data for folder and end point child node (filters). Also I created custom context menu, with some functions for different types of node. In this context menu I defined variable check and with help this variable I set restrictions for operations with node. The full code of context menu looks like:
$scope.contextMenu = {
"create": {
"label": "Create Folder",
"icon": "ico/folder.png",
"action": function (data) {
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference),
id = obj['original']['id'];
var check = obj['original']['folderId'];
if (typeof check == "undefined") {
obj = {
text: prompt("put folder name"),
parent: id
};
eventService.createFolder(obj);
setTimeout(function () {
getTreeData();
$scope.load();
}, 100);
}
else {
alert("This function is not available");
return false
}
// inst.refresh(true)
}
},
"rename": {
"label": "Rename Folder",
"icon": "ico/folder.png",
"action": function (data) {
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference),
check = obj['original']['folderId'];
if (typeof check == "undefined") {
var rename = {
id: obj.id,
text: prompt("put your name")
};
eventService.modifyFolder(rename);
inst.rename_node(obj, rename.text);
}
else {
alert("This function is not available");
return false
}
}
},
"delete": {
"label": "Delete Folder",
"icon": "ico/folder.png",
"action": function (data) {
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference),
node = inst.get_selected(),
check = obj['original']['folderId'];
if (typeof check == "undefined") {
if (!node.length) {
return false;
}
eventService.deleteFolder(node);
inst.delete_node(node);
}
else {
alert("This function is not available");
return false
}
}
},
"store": {
"label": "Store Filter",
"icon": "ico/file.png",
"action": function (data) {
$scope.saveStateString();
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference),
id = obj['original']['id'],
check = obj['original']['folderId'];
if (typeof check == "undefined") {
obj = {
body: $scope.state,
folderId: id,
text: prompt("put filter name")
};
// console.log(obj.body);
setTimeout(function () {
eventService.storeFilter(obj);
}, 1000);
setTimeout(function () {
getTreeData();
$scope.load();
alert("click to public filters to refresh the tree")
}, 1500)
} else {
alert("This function is not available");
return false
}
}
},
"remove": {
"label": "Remove Filter",
"icon": "ico/file.png",
"action": function (data) {
var inst = $.jstree.reference(data.reference),
node = inst.get_selected(),
obj = inst.get_node(data.reference),
check = obj['original']['folderId'];
if (typeof check == "undefined") {
alert("This function is not available");
return false
} else {
if (!node.length) {
return false;
}
eventService.deleteFilter(node);
inst.delete_node(node);
}
}
}
};
Now I'm trying to split this context menu by type of node, that for each node I could see different context menu, I found some solutions here and it says:
$('#jstree').jstree({
'contextmenu' : {
'items' : customMenu
},
'plugins' : ['contextmenu', 'types'],
'types' : {
'#' : { /* options */ },
'level_1' : { /* options */ },
'level_2' : { /* options */ }
// etc...
}
});
function customMenu(node)
{
var items = {
'item1' : {
'label' : 'item1',
'action' : function () { /* action */ }
},
'item2' : {
'label' : 'item2',
'action' : function () { /* action */ }
}
}
if (node.type === 'level_1') {
delete items.item2;
} else if (node.type === 'level_2') {
delete items.item1;
}
return items;
}
I was trying to repeat this way in my app but always see "undefined" instead context menu.
Could anybody help me please to resolve my problem? Plunker with my code
Be sure you are using working jstree directive. I replaced mistakes in your directive
if (config.plugins.indexOf('contextmenu') >= 0) {
if (a.treeContextmenu) {
config.contextmenu = s[a.treeContextmenu];
}
}
// if (config.plugins.indexOf('contextmenu') >= 0) {
// if (a.treeContextmenu) {
// config.contextmenu = config.contextmenu || {};
//
// if (a.treeContextmenuaction != undefined) {
// config.contextmenu.items = function(e) {
// return s.$eval(a.treeContextmenuaction)(e);
// }
// } else {
// config.contextmenu.items = function() {
// return s[a.treeContextmenu];
// }
// }
// }
// }
Your code should look like
$scope.contextMenu = {
"items": function custom (node){
// your menu
}
if(something){
// do whatever
}
return items
}
This is your working plunker!

Undefined variable in modularized script

I've been working at making this script more modularized toady, and I am running into an error. Am I ordering my logic incorrectly?
Error Msg
Uncaught ReferenceError: accountId is not defined
Related Script Line
_.each(_.omit(accounts, _.keys(result.data.accounts)), function (account) {
accounts[accountId].push([result.timestamp.valueOf(), 0]);
});
Script
var debug = 0;
function paramsStr(p) {
var first = true;
var s = '';
_.each(p,function (value,key) {
if (!value) {
return;
}
if (first) {
s += '?';
first = false;
} else {
s += '&';
}
s += key+'='+value;
});
return s;
};
function parseReport(data)
{
var split = data.split('\n');
var results = [];
_.each(split,function (row) {
if (!row || row == "") {
return;
}
var myRow = JSON.parse(row);
myRow.timestamp = moment.utc(myRow.timestamp);
results.push(myRow);
});
return results;
}
function loadReport(report,granularity,startTime,endTime) {
if (debug && _.has(mock.reports,report) && _.has(mock.reports[report],granularity)) {
return jQuery.Deferred().resolve(parseReport(mock.reports[report][granularity])).promise();
}
var params = {
granularity : granularity
};
if (startTime) {
params['start-time'] = startTime.toISOString();
}
if (endTime) {
params['end-time'] = endTime.toISOString();
}
var url = '//analytics.locuslabs.com/api/reports/'+report+paramsStr(params);
return $.ajax({
url : url,
dataType : 'text'
}).then(function (data) {
return parseReport(data);
});
};
$(document).ready(function () {
var placeholder = $(".graph");
var oneMonth = moment().utc().subtract(1, 'months');
var twoWeeks = moment().utc().subtract(2, 'weeks');
//Function call to get the current time
function dateNow(target,timeFormat){
$(placeholder).siblings(target).text(moment(Date.now()).format(timeFormat));
}
function pollData(apiRoot,increment,startDate,label){
loadReport(apiRoot,increment, startDate).then(function (results) {
var totals = [];
var accounts = {};
_.each(results, function (result) {
totals.push([
result.timestamp.valueOf(),
result.data.total
]);
_.each(result.data.accounts, function (account, accountId) {
if (!_.has(accounts, accountId)) {
accounts[accountId] = {
label: account.account.name,
data: []
};
}
accounts[accountId].data.push([
result.timestamp.valueOf(),
account.total
]);
});
_.each(_.omit(accounts, _.keys(result.data.accounts)), function (account) {
accounts[accountId].push([result.timestamp.valueOf(), 0]);
});
});
var data = [{
data: totals,
label: label
}];
_.each(accounts, function (account) {
data.push(account);
});
$(this > ".graph").plot(data, {
grid: {
hoverable: true
},
tooltip: {
show: true
},
xaxis: {
mode: "time"
},
yaxis: {
axisLabel: label
},
legend: {
container: $(this > ".legend")
},
selection: {
mode: "x"
}
});
});
// Reload function within pollData function
document.getElementById(apiRoot + "-reload").addEventListener("click", function() {
pollData(apiRoot,increment,startDate,label);
dateNow(".status","M/D/YYYY H:mm Z");
}, false);
}
//Load Reports
pollData('total-installs', 'day', oneMonth, "Total Installs");
pollData('installs', 'hour', twoWeeks, "Installs (by hour)");
pollData('sessions', 'day', twoWeeks, "Sessions");
pollData('sessions-length', 'day', twoWeeks, "Session Length");
// Selection Feature
// TODO: Add Zoom to selection
// TODO: Overview of Available Data when zoomed.
placeholder.bind("plotselected", function (event, ranges) {
var begin = ranges.xaxis.from.valueOf();
var end = ranges.xaxis.to.valueOf();
$(this).siblings(".selection").text(moment(begin).format("M/D/YYYY H:mm Z") + " to " + moment(end).format("M/D/YYYY H:mm Z"));
/*
var zoom = $("#zoom").prop("checked");
if (zoom) {
$.each(plot.getXAxes(), function(_, axis) {
var opts = axis.options;
opts.min = ranges.xaxis.from;
opts.max = ranges.xaxis.to;
});
plot.setupGrid();
plot.draw();
plot.clearSelection();
}
*/
});
// Update on Initial Poll
// TODO: Ask for location and provide local time.
dateNow(".status","M/D/YYYY H:mm Z");
});
You have no accountId parameter in your function
function (account) {
accounts[accountId].push([result.timestamp.valueOf(), 0]);

While trying to download a page, why doesn't this code alert test?

I have to download myURLString (http://www.google.com/search?q=http://www.google.com/&btnG=Search+Directory&hl=en&cat=gwd%2FTop).
function getcontents(myURLString) {
var gChannel;
var ioService = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var uri = ioService.newURI(myURLString, null, null);
gChannel = ioService.newChannelFromURI(uri);
var listener = new StreamListener(callbackFunc);
gChannel.notificationCallbacks = listener;
gChannel.asyncOpen(listener, null);
function StreamListener(aCallbackFunc) {
this.mCallbackFunc = aCallbackFunc;
}
StreamListener.prototype = {
mData: "",
onStartRequest: function (aRequest, aContext) {
this.mData = "";
},
onDataAvailable: function (aRequest, aContext, aStream, aSourceOffset, aLength) {
var scriptableInputStream = Components.classes["#mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
scriptableInputStream.init(aStream);
this.mData += scriptableInputStream.read(aLength);
},
onStopRequest: function (aRequest, aContext, aStatus) {
if (Components.isSuccessCode(aStatus)) {
this.mCallbackFunc(this.mData);
alert('test');
} else {
this.mCallbackFunc(null);
}
gChannel = null;
},
onChannelRedirect: function (aOldChannel, aNewChannel, aFlags) {
gChannel = aNewChannel;
},
getInterface: function (aIID) {
try {
return this.QueryInterface(aIID);
} catch (e) {
throw Components.results.NS_NOINTERFACE;
}
},
onProgress : function (aRequest, aContext, aProgress, aProgressMax) { },
onStatus : function (aRequest, aContext, aStatus, aStatusArg) { },
onRedirect : function (aOldChannel, aNewChannel) { },
QueryInterface : function(aIID) {
if (aIID.equals(Components.interfaces.nsISupports) ||
aIID.equals(Components.interfaces.nsIInterfaceRequestor) ||
aIID.equals(Components.interfaces.nsIChannelEventSink) ||
aIID.equals(Components.interfaces.nsIProgressEventSink) ||
aIID.equals(Components.interfaces.nsIHttpEventSink) ||
aIID.equals(Components.interfaces.nsIStreamListener))
return this;
throw Components.results.NS_NOINTERFACE;
}
};
}
I'm thinking this.mData should have the page's contents, but I can't alert it, so I'm trying first to alert test. What is wrong?
UPDATE: I'm trying now...
function callbackFunc(pagecontents) {
alert(pagecontents);
}
...but it isn't called. Why?
I suspect you are getting an error since StreamListener is defined after you call new StreamListener(...). Have you set the proper developer preferences?

Categories

Resources