In jquery after finish of first loop call some other function - javascript

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.

Related

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).

Do something after all FB API calls finish

I have some functions that are making some Facebook API calls, and an init one:
var fbAPI = {
init: function () {
this.friendList(), this.friendCount();
},
friendList: function (closure) {
var _self = this;
return FB.api(
"/me/taggable_friends",
function (data) {
_self.setFriends(data);
closure(data);
}
);
},
friendCount: function (closure) {
var _self = this;
return FB.api(
"/me/friends",
function (data) {
_self.setFriendsCount(data.summary.total_count);
closure(data);
}
);
},
friends: null,
friendsCount: null,
setFriends: function (data) {
this.friends = data;
},
setFriendsCount: function (count) {
this.friendsCount = count;
}
};
When all the calls are finished I want to remove the loading overlay.
Something like:
(fbAPI.init()).finish(function(){
//do something
});
How can I achieve this?

printing all records using only one alert

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(', '))

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]);

could not update a variable in an angular service with ajax response data and use is to filter

i'm using the same code from this article (internationalization with angularjs)
...
but i need the "tables" variable to be fetched from an ajax request response using "$http get" but couldn't !! ... here is the code,
var xlat = angular.module('xlat', []);
xlat.factory('xlatService', function ($http) {
var currentLanguage = 'en';
// var tables = $.extend(true, {}, initialXlatTables);
var tables = {
'en': {
'textKeys.events': 'Events'
}
};
var service = {
getData: function () {
var req = {
method: 'GET',
url: 'local/en_US.php',
cache: true,
headers: {
'Content-Type': 'json'
}
};
$http(req).success(function (data) {
tables = data;
});
},
setCurrentLanguage: function (newCurrentLanguage) {
currentLanguage = newCurrentLanguage;
},
getCurrentLanguage: function () {
return currentLanguage;
},
xlat: function (label, parameters) {
service.getData();
if (parameters === null || $.isEmptyObject(parameters)) {
return tables[currentLanguage][label];
} else {
return $interpolate(tables[currentLanguage][label])(parameters);
}
}
};
return service;
});
but the variable "tables" does not change when i use the filter...
var xlat = angular.module('xlat', []);
xlat.filter('xlat', ['xlatService', function (xlatService) {
return function (label, parameters) {
return xlatService.xlat(label, parameters);
};
}]);
Try this one:
var xlat = angular.module('xlat', []);
xlat.filter('xlat', ['xlatService', function (xlatService) {
function myfiler(label, parameters) {
return xlatService.xlat(label, parameters);
};
myfiler.$stateful = true;
return myfilter;
}]);
Stateful filters -
https://code.angularjs.org/1.3.9/docs/guide/filter
Secod: you should load tables in factory method not in xlat function.

Categories

Resources