Sorting results from SharePoint RestAPI - javascript

I'm trying to build some semi-dynamic staff directory pages from a Sharepoint List, using their REST API.
I know enough Javascript to get me in trouble, so I have a feeling my solution is not as elegant as it could be and probably not ideal.
The goal is to allow our web editors to create unique pages for various departments by simply adding a short script and the employee's email address. Another option I've thought about is simply adding a field in the list for each program but it's not consistent enough across the board, so being able to set the list and sort on each page is probably the best option.
The solution works just fine but occasionally the sort order gets out of wack, I'm guessing because of the order the script reads the list.
Here's the front end code:
<script type="text/javascript"
src="getstaffdirectory2.js"></script>
<script>
$(document).ready(function() {
GetStaffDirectory('email1#dcccd.edu');
GetStaffDirectory('email2#dcccd.edu');
GetStaffDirectory('email3#dcccd.edu');
GetStaffDirectory('email4#dcccd.edu');
GetStaffDirectory('email5#dcccd.edu');
});
</script>
<div class="white-space-2"></div>
<div class="row">
<div id="GetStaffDirectory"></div>
</div>
Rather un-elegant? :-)
Here's the script:
function GetStaffDirectory(UserEmail) {
var res;
var selectStr = '$select=';
var expandStr = '$expand=';
var filterStr = '$filter=(EMAIL eq \''+UserEmail+'\')';
var requestURL = '/_api/web/lists/GetByTitle(\'Staff
Directory\')/items?'+filterStr; // + '?' + selectStr + '&' + expandStr + '&'
+ filterStr;
console.log(requestURL);
$.ajax({
url: requestURL,
headers: {
Accept: 'application/json;odata=verbose'
},
method: 'GET',
//Success Function
success: function (data) {
res = data.d.results;
console.log(res);
// College Name Function
switch(res[0].LOC){
case "BHC" : {
loc1="Brookhaven College";
break;
}
case "CVC" : {
loc1="Cedar Valley College";
break;
}
case "EFC" : {
loc1="Eastfield College";
break;
}
case "ECC" : {
loc1="El Centro College";
break;
}
case "MVC" : {
loc1="Mountain View College";
break;
}
case "NLC" : {
loc1="North Lake College";
break;
}
case "RLC" : {
loc1="Richland College";
break;
}
case "DCO" : {
loc1="Lecroy Center/ Dallas Colleges Online";
break;
}
case "DSC" : {
loc1="District Service Center";
break;
}
case "DO" : {
loc1="District Office";
break;
}
default : {
loc1="";
break;
}
}
if((res[0].Office_x0020_Number == null)||(res[0].Office_x0020_Number
== undefined)){
officeNum = "";
}
else {
officeNum = '<li class="contact-office">' +
res[0].Office_x0020_Number + '</li>\n'
}
if((res[0].biolink == null)||(res[0].biolink == undefined)){
biolinkURL = "";
}
else {
biolinkURL = '<li class="contact-bio">Online Bio<span class="sr-only"> for ' + res[0].Title + '</span></li>\n'
}
if((res[0].staff_x002d_photo == null)||(res[0].staff_x002d_photo
== undefined)){
staffphoto = '/logo-' +
res[0].LOC + '-square.svg'
}
else {
staffphoto = res[0].staff_x002d_photo;
}
var contactString =
'<div class="col-sm-4">\n' +
'<div class="contact-box height-sm-400 ' + res[0].LOC + '">\n' +
'<img class="contact-photo" src="' + staffphoto + '">\n' +
'<div class="contact-name">' + res[0].FIRST + ' ' + res[0].Title +
'</div>\n' +
'<div class="contact-title">' + res[0].Title1 + '</div>\n' +
'<div class="contact-dept">' + res[0].department + '</div>\n' +
'<ul class="contact-info">\n' +
'<li class="contact-location">' + loc1 + '</li>\n' +
officeNum +
'<li class="contact-email"><a href="mailto:' + res[0].EMAIL + '">' +
res[0].EMAIL + '</a></li>\n' +
'<li class="contact-phone">' + res[0].PHONE + '</li>\n' +
biolinkURL +
'</ul>\n</div>\n</div>\n</div>\n';
$("#GetStaffDirectory").append(contactString);
},
//Error Function
error: function (jQxhr, errorCode, errorThrown) {
res = jQxhr;
console.log(res);
$("#AjaxLoader0").hide();
$(".AjaxMessage").html(errorThrown);
},
dataType: 'json' //Make me a JSON
});
};
Is there an easier way to ensure the script pulls the data in the order listed on the page? I'm guessing there's some method with an array but I'm not as familiar with how they work.

It is better to do everything you need in one request for better performance. Change GetStaffDirectory() to work with a string array and filter like this;
var filterStr = '$filter=((EMAIL eq userEmails[0]) or (EMAIL eq userEmails[1]))'
And also, you can now add your sorting logic;
$orderby=EMAIL desc

Related

Want to use YDN-db database instead of Ajax with Select2

I want to use YDN-db with select2, i tried few options but unable to sort.
So i want to use executeSql command as below
APP.db.executeSql("SELECT * FROM products WHERE name like '%test%'").then(function(results) {
//something
}
so i tried following in last (i already used other tweaks of it aswell)
$('#add_product_id').select2({
data:function (params) {
console.log(params);
APP.db.executeSql("SELECT * FROM products WHERE name = '"+params+"'").then(function(resultRows) {
if(resultRows.length > 0) {
$.each( resultRows, function( i, productRow ) {
console.log(productRow);
var title ='<span class="result-title">' + productRow.name + '</span>';
var price = '<span class="result-price">' + productRow.price + '</span>'
;
var sku = '<span class="result-sku">' + pos_i18n[60] + ' ' + productRow.sku + '</span>';
var stock = '<span class="result-stock">' + pos_i18n[61] + ' ' + productRow.stock_quantity + '</span>';
var firstRow = '<div class="result-row first">' + title + price + '</div>';
var secondRow = '<div class="result-row second">' + sku + stock + '</div>';
});
}
});
},
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 3,
cache: true,
multiple: true,
}).change(function () {
var val = $(this).select2('data');
$(this).html('');
if (!empty(val)) {
val = is_array(val) ? val[0] : val;
}
});
YDN query executed by requested parameter not coming log which user actually types on search2 field,
console.log(params);
Please can any one guide me how can i use YDN-db instead of Ajax with Select2?

I have javascript code to view a news from RSS as a vertical list. I need help to move the list of topics as horizontal one by one, in one line

I have javascript code to view a news from RSS as a vertical list.
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
DescCharacterLimit: 0,
TitleLinkTarget: "_blank",
DateFormat: "",
DateFormatLang:"en"
}, opt);
var id = $(this).attr("id"), i, s = "", dt;
$("#" + id).empty();
if (def.FeedUrl == undefined) return;
$("#" + id).append('<img src="loader.gif" />');
var YQLstr = 'SELECT channel.item FROM feednormalizer WHERE output="rss_2.0" AND url ="' + def.FeedUrl + '" LIMIT ' + def.MaxCount;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(YQLstr) + "&format=json&diagnostics=false&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
if (!(data.query.results.rss instanceof Array)) {
data.query.results.rss = [data.query.results.rss];
}
$.each(data.query.results.rss, function (e, itm) {
s += '<li><div class="itemTitle"><a href="' + itm.channel.item.link + '" target="' + def.TitleLinkTarget + '" >' + itm.channel.item.title + '</a></div>';
if (def.ShowPubDate){
dt = new Date(itm.channel.item.pubDate);
s += '<div class="itemDate">';
if ($.trim(def.DateFormat).length > 0) {
try {
moment.lang(def.DateFormatLang);
s += moment(dt).format(def.DateFormat);
}
catch (e){s += dt.toLocaleDateString();}
}
else {
s += dt.toLocaleDateString();
}
s += '</div>';
}
if (def.ShowDesc) {
s += '<div class="itemContent">';
if (def.DescCharacterLimit > 0 && itm.channel.item.description.length > def.DescCharacterLimit) {
s += itm.channel.item.description.substring(0, def.DescCharacterLimit) + '...';
}
else {
s += itm.channel.item.description;
}
s += '</div>';
}
});
$("#" + id).append('<ul class="feedEkList">' + s + '</ul>');
}
});
};
})(jQuery);
I need help to move the list of topics as horizontal one by one, in one line. by used javascript code. this code display just 5 topics, which I need it, but I have problem to how can I movement it as horizontal.

No response from 2nd ajax request

I am getting no response from a 2nd ajax request. I am trying to display an google information window on google map that contains only a single tab when a certain criteria is matched otherwise I want to display two tabs. I thought I could easily implement this with another marker function with tailored behaviour, but I receive no response. Any help on this is always appreciated. Thanks in advance.
// click event handler
google.maps.event.addListener(marker, 'click', function () {
var ecoli_array = [];
var marker = this;
var str = "";
var beach_status; // beach_status flag
// load gif before ajax request completes
infoWindow.setContent('<img src="img/loading.gif" alt="loading data"/>');
infoWindow.open(map, marker);
// override beach data when a beach is closed
beach_status = this.getBeachStatus();
beach_status = beach_status.toLowerCase();
if (beach_status === 'closed') {
str = [
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>' + this.status_description + '</p>'
].join('');
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
} else {
// chained ajax invocations
if ( this.displayOnlyAlgaeResults === false ) {
// Standard Use case
$.when(this.getEcoliData(), this.getAlgaeData()).done(function (data1, data2) {
str += marker.getHeader() + marker.afterGetEcoliData(data1[0].rows);
str += marker.afterGetAlgaeData(data2[0].rows);
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
// render tabs UI
$(".tabs").tabs({ selected: 0 });
}); // end when call
}else{
// Algae Only Use Case
var d = this.getOnlyAlgaeData();
console.log(d);
$.when( this.getOnlyAlgaeData() ).done(function ( rsp ) {
//console.log(rsp);
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp[0].rows );
//str += marker.afterGetOnlyAlgaeData(data2[0].rows);
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
// render tabs UI
$(".tabs").tabs({ selected: 0 });
}); // end when call
} // end inner if else
} // end outer if else
}); // End click event handler
getOnlyAlgaeData: function () { // begin getAlgaeData
var obj;
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=xxxxx&callback=?';
var whereClause = " WHERE 'Beach_ID' = " + this.beach_id;
var query = "SELECT * FROM xxxx "
+ whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
// ecoli request
return $.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp'
});
}, // end getAlgaeData method
// added afterGetOnlyAlgaeData
afterGetOnlyAlgaeData: function (data) {
var algae_rows_str = "";
algae_rows = data;
var algae_rows_str = [
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<table id="algae_table " class="data">',
'<tr>',
'<th>Sample Date</th>',
'<th class="centerText">Blue Green Algae Cells <br/>(cells/ mL) </th>',
'<th>Recreational Water Quality Objective <br/>(100,000 cells/mL)</th>',
'<th class="centerText">Algal Toxin Microcystin <br/> (&#956g/L)</th>',
'<th>Recreational Water Quality Objective <br/> (20 &#956g/L)</th>', // &mu instead of u
'</tr>'
].join('');
//console.log(algae_rows);
if (typeof algae_rows === 'undefined') {
algae_rows_str = [
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>This season, no algal blooms have been reported at this beach.</p>',
'</div>',
'</div>',
'</div>',
'</div>'
].join('');
} else {
for (var i = 0; i < algae_rows.length; i++) {
//console.log(rows[i]);
//algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td class="centerText">' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + checkAlgaeToxinForAdvisory(algae_rows[i][4]) + '</td><td class="centerText">' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + checkBlueGreenAlgaeCellsForAdvisory(algae_rows[i][6]) + '</td></tr>';
algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td class="centerText">' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + checkBlueGreenAlgaeCellsForAdvisory(algae_rows[i][6]) + '</td><td class="centerText">' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + checkAlgaeToxinForAdvisory(algae_rows[i][4]) + '</td></tr>';
}
algae_rows_str += '</table>'
algae_rows_str += '</div></div></div>';
//return algae_rows_str;
} //end if
return algae_rows_str;
}, // end afterGetOnlyAlgaeData
}); // ====================end marker
I essentially copied two identical functions that work, gave them a slightly different name and customized each function to display 1 tab instead of two, but I get no response.
Thoughts?
thanks for the help, it ended up being something simple.
I was incorrectly referencing the response. Ie. I change the following line:
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp[0].rows );
to
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp.rows );
Geez!

In Javascript how can I stop any further iterations from firing until a condition is met

I have been trying to get the following issue resolved for the past 2 weeks and am getting nowhere, hopefully someone can point me in the right direction;
I have a single page application that uses JS and jQuery alongwith xml logic conditions and actions.
With JS allowing for functions to act asynchronously is great but I need to solve an issue;
When a user clicks an element the js goes through the xml and finds nodes related to the element ID, checks if the condition set is met and fires associated actions. A snippet of XML iis shown below;
<block id="10000005" triggerID="125">
<ConditionsAndActions name="Default" setIndex="0">
<Conditions>
</Conditions>
<Actions>
<Action actionIndex="0" type="AskForConfirmation" message="Are you sure?"/>
<Action actionIndex="0" type="NewRecord" />
</Actions>
</ConditionsAndActions>
</block>
The abiove indicates when '#btn125' is clicked fire AskForConfirmation function then if user clicks the confirmation button, process the manual record function.
The actions are traversed by a loop and I need to for AskForConfirmation stop the loop continuing until either user completed acknowledgement or if user gives a negative response or a 30 second period lapses then the loop is abandoned.
I have tried setTimeout using a variable to control firing the next action without success and cannot get my head around async/await if this is feasable please guide me on how to do it.
I include the action firing loop below;
function triggerActions(callType, tags, iC1, iC2, iC3, iC4) {
for (var iA1 = 0; iA1 < tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes.length; iA1++) {
if (tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].nodeName === "Actions") {
for (var iA2 = 0; iA2 < tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes.length; iA2++) {
if ($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("type") !== null) {
switch ($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("type")) {
case "ChangeVisibility":
if (debugMode) {
loggingAction('log','NOTIFICATION : ' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("element") + ' visibility amended.');
}
eval('$("#' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("element") + '").' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].chidNodes[iA1].childNodes[iA2]).attr("effect") + '();');
break;
case "commentBox":
if (debugMode) {
loggingAction('log','NOTIFICATION : Comment box for ' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("name") + ' found in configuration');
loggingAction('log','comment log');
}
break;
case "DisplayAlert":
if (debugMode) {
loggingAction('log','NOTIFICATION : Lightbox stating: ' + variableConversion(($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("message"))) + ' output');
}
var alertMessage = '<h2 class="text-center">ALERT:</h2><p class="text-center">' + variableConversion(($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("message"))) + '</p>';
$.colorbox({
html: alertMessage
});
$('#cboxContent').removeClass('errorMessage');
break;
case "DataQuery":
if (debugMode && (($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("destination")).length !== 0)) {
destination = '{{' + ($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("destination")) + '}}';
loggingAction('log','NOTIFICATION : Data Query initiated with destination = "' + destination + '", destinationControl = "' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("destinationControl") + '",query number = "' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("queryNumber") + '", parameters ="' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("parameters") + ' " and values = "' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("values") + '".');
}
getRunQuery($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("destination"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("destinationControl"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("parameters"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("queryNumber"), sessionID);
break;
case "DataSource":
if (debugMode) {
loggingAction('log','NOTIFICATION : Data Source Action');
}
break;
case "DispositionCall":
sendDisposition($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("outcome"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("callbackNumber"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("callbackNumberControl"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("callbackTime"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("callbackTimeControl"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("personalCallback"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("returnData"));
break;
case "GetRecord":
var URN = ($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2])).attr("URN");
if (gridValueSelected.length > 0) {
URN = gridValueSelected;
}
if (debugMode) {
loggingAction('info','INFORMATION : Get Record request initiated with URN return of "' + URN + '".');
}
rid = generateRID(), message = 'type: "GetRecord", RID: ' + rid + ', SID: ' + sessionID + ', URN:"' + URN + '"';
activeRequests.push(rid + ':GetRecord');
socket.send(message);
if (debugMode) {
loggingAction('info','INFORMATION : Get Record message sent to server "' + message + '".');
}
break;
case "GoAvailable":
if (debugMode) {
if (debugMode) { loggingAction('log','NOTIFICATION : Setting Agent status to Available.'); }
rid = generateRID(), message = 'type:"GoAvailable",RID:' + rid + ',SID:' + sessionID;
serverComms("outbound", message, rid, "GoAvailable");
if (debugMode) { loggingAction('log','NOTIFICATION : Message sent to server - "' + message + '".'); }
}
break;
case "HangUp":
if (debugMode) {
loggingAction('log','NOTIFICATION : Hang up call requested.');
}
$.colorbox({
html: '<h2 class="confirmation text-center">Confirmation:</h2><p class="confirmation text-center">Call hung up.</p>'
});
$('#cboxContent').removeClass('errorMessage');
break;
case "LogOut":
if (debugMode) {
loggingAction('log','NOTIFICATION : Agent has requested to Log out of script.');
}
logOut();
break;
case "MoveToPanel":
if (debugMode) {
loggingAction('log','NOTIFICATION : Action to Move to Panel #pnl' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("panelID") + ' triggered.');
}
var parser = new DOMParser(),
xmlLogic = parser.parseFromString(scriptXML, "text/xml"),
tags = xmlLogic.getElementsByTagName('*');
$(document).ready(function () {
for (var i0 = 1; i0 < tags.length; i0++) {
switch (tags[i0].nodeName) {
case "Button":
updateVariableOutput('#' + $(tags[i0]).attr("id"), $(tags[i0]).attr("name"));
break;
case "inputField":
updateVariableOutput('#' + $(tags[i0]).attr("id"), $(tags[i0]).attr("label"));
break;
case "textBlock":
updateVariableOutput('#' + $(tags[i0]).attr("id"), $(tags[i0]).attr("text"));
break;
}
}
});
eval('$("#pnl' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("panelID") + '").parent().children().hide(); $("#pnl' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("panelID") + '").show();');
gridValueSelected = '';
$('.selectedRow').removeClass('selectedRow');
$('table').children().remove();
$('table').removeClass('jsgrid');
break;
case "MoveToScriptWindow":
if (debugMode) {
loggingAction('log','NOTIFICATION :Action to Move to Window "#win' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("panelID") + '" has been triggered.');
}
eval('$("#win' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("panelID") + '").parent().children().hide(); $("#win' + $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("panelID") + '").show();');
gridValueSelected = '';
$('.selectedRow').removeClass('selectedRow');
$('table').children().remove();
$('table').removeClass('jsgrid');
break;
case "OpenBrowserWindow":
openNewWindow($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("URL"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("toolbar"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("addressBar"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("toolbar"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("addressBar"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("toolbar"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("addressBar"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("toolbar"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("addressBar"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("width"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("height"));
if (debugMode) {
loggingAction('log','INFORMATION : "' + variableConversion($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("URL")) + '" opened in new window.');
}
break;
case "SetFieldParameter":
if (debugMode) {
loggingAction('log','NOTIFICATION : Field Parameter Set');
}
break;
case "SetTextBox":
if (debugMode) {
loggingAction('log','NOTIFICATION : Set Text Box Action');
}
break;
case "SetVariable":
if (gridValueSelected !== '') {
var variableName = $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("variable")
if (debugMode) {
loggingAction('log','NOTIFICATION : The variable to have selected grid value associated with it is "' + variableName + '".');
}
variableNameSplit = variableName.split('.');
if (debugMode) {
loggingAction('info','INFORMATION : The Object to recieve the variable is "' + variableNameSplit[1] + '".');
loggingAction('info','INFORMATION : The key for the variable is "' + variableNameSplit[1] + '".');
}
if ((variableNameSplit[0] === 'Script') || (variableNameSplit[0] === 'SCRIPT')) {
addScriptVariable(variableNameSplit[1], gridValueSelected);
}
} else {
loggingAction('log','NOTIFICATION : Set Variable Value function initiated.');
if ($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("value") !== '') {
var variableName = $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("variable"),
variableValue = variableConversion($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("value"));
if (debugMode) {
loggingAction('log','NOTIFICATION : ' + variableName + ' set to "' + variableValue + '".');
}
eval(variableName + '="' + variableValue + '"');
} else if ($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("controlID") !== '') {
var variableName = $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("variable"),
variableValue = $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("controlID");
variableValue = eval('$("#txt' + variableValue + '").val()');
if (debugMode) {
loggingAction('log',' NOTIFICATION : The value of the variable to be passed to ' + variableName + ' is "' + variableValue + '".');
}
eval(variableName + '="' + variableValue + '"');
}
}
break;
case "UpdateWebFrame":
if (debugMode) {
loggingAction('info','INFORMATION : iFrame update initiated to load ' + variableConversion($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("URL")) + '.')
}
updateIFrame($(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("URL"), $(tags[0].childNodes[iC1].childNodes[iC2].childNodes[iC3].childNodes[iA1].childNodes[iA2]).attr("destinationControl"));
break;
}
}
}
}
}
}
A simplified example of what I'm looking to achieve is below;
JS;
var blocker = 'no';
function askForConfirmation() {
$('#Interaction').fadeIn();
}
function manualRecord() {
console.log('Request new record')}
function responseReceived(acknowledgemntValue){
$('#Interaction').fadeOut();
}
$(document).ready(function(){
$('#btn69').click(function(){
askForConfirmation();
});
$('#accept').click(function(){
blocker = 'no';
responseReceived();
alert(blocker);
});
$('#decline').click(function(){
blocker = 'yes';
responseReceived();
alert(blocker);
});
});
html;
<!DOCTYPE html>
<head>
<title>Sandbox</title>
</head>
<body>
<header>
<h2>Sandbox testing</h2>
</header>
<main>
<button id="btn69">Request Manual Record</button>
<div id="Interaction" style="display:none;">
<p>Please confirm you wish to create manual record</p>
<p><button id="accept">Accept</button><button id="decline">Decline</button></p>
</div>
<div id="blockerState"></div>
</main>
<footer>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="sandscript.js"></script>
</footer>
</body>
Loop won't pause for async operation(like setTimeout) to be completed This is just how JavaScript(single threaded language) executes the statement. Therefore setTimeout in a loop is not going to work.
Though Its not clear why you are putting the logic of triggerActions inside for loop if it is just a single action of button click and probably only one corresponding action from xml will get triggered.
Whatever the scenario or business requirement you have may be you can tweak the triggerActions as below to get it working in current scenario.
The idea is to store the indexes with which the for loop to be resumed when you wait for user for particular condition and then call the triggerActions again to resume the loop from where it was left.
var startIndexOuterLoop, startIndexInnerLoop; //hold the reference of for loop index for the `AskForConfirmation` scenario
function triggerActions(params..., resumeMode) {
var iA1, iA2;
if (resumeMode) {
iA1 = startIndexOuterLoop;
iA2 = startIndexInnerLoop;
} else {
iA1 = 0;
iA2 =
}
var outerLoopIterateOnce = false;
for (; i < ...; i++) {
//reset iA2 to 0 onward, right
if (outerLoopIterateOnce) {
iA2 = 0;
}
outerLoopIterateOnce = true;
for (; i < ...; i++) {
// ... statements
if ( /*condition for AskForConfirmation */ ) {
handleAskForConfirmation(iA1, iA2);
return; //exit from function
}
}
}
}
function handleAskForConfirmation(iA1, iA2) {
startIndexOuterLoop = iA1+1;//1 added so as to continue next iteration
startIndexInnerLoop = iA2+1;
// add logic for wait time out etc
//once thats expired or as per business logic call triggerActions again with one more parameter as true to resume the foor loop indirectly
triggerActions(params..., true);
}
I removed the issue by tracking the action number and adding a counter mechanism to track status which is updated on action completion then fires the next action

How to sort data of json object and display accordingly in html?

This is my ajax:
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php",
data: data,
success: function (data) {
$("#main_content").slideUp("normal",function(){
//$(".the-return").html("<br />JSON: " + data+"<br/>");
for (i = 0; i < data.length; i++) {
$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode+ "<br/>Reputation:" + data[i].reputation+"<br/>Review Plus:" + data[i].plus+"<br/>Review Negative:" + data[i].neg+"<br/><h1>Availability</h1>Week Morning:" + data[i].weekM+"<br/>Week Afternoon:" + data[i].weekA+"<br/>Week Evening:" + data[i].weekE+"<br/>Weekend Morning:" + data[i].endM+"<br/>Weekend Afternoon:" + data[i].endA+"<br/>Week Evening:" + data[i].endE+"</div>");
//alert(data[i].name)
}
});
}
});
return false;
});
Above is my ajax. Now this is returning result from query that sorts by postcode by default.
Now when the result displayed, I want to let the user to sort it out by reputation, review and so on..How do I do that.
Put it in a simple way, I just need to alter the order by clause in the query so that it can sort by user selection. What's the easiest way to do it please?
How can I manipulate below part where it appends the result to a div called -the-return so that it sorts by whatever key user use?: Note-> I'm presenting the result in <div> block and not in table.
$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode+ "<br/>Reputation:" + data[i].reputation+"<br/>Review Plus:" + data[i].plus+"<br/>Review Negative:" + data[i].neg+"<br/><h1>Availability</h1>Week Morning:" + data[i].weekM+"<br/>Week Afternoon:" + data[i].weekA+"<br/>Week Evening:" + data[i].weekE+"<br/>Weekend Morning:" + data[i].endM+"<br/>Weekend Afternoon:" + data[i].endA+"<br/>Week Evening:" + data[i].endE+"</div>");
WHat I tried:
success: function (data) {
//I used a function to sort//
data.sort(function (a, b) {
var retVal = 0;
switch (sortOption) {
case 1:
retVal = a.property > b.property ? 1 : (a.property < b.property ? -1 : 0);
break;
// .... many cases here
}
return retVal;
});
//sort function ends here//
$("#main_content").slideUp("normal", function () {
for (i = 0; i < data.length; i++) {
$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode + "<br/>Reputation:" + data[i].reputation + "<br/>Review Plus:" + data[i].plus + "<br/>Review Negative:" + data[i].neg + "<br/><h1>Availability</h1>Week Morning:" + data[i].weekM + "<br/>Week Afternoon:" + data[i].weekA + "<br/>Week Evening:" + data[i].weekE + "<br/>Weekend Morning:" + data[i].endM + "<br/>Weekend Afternoon:" + data[i].endA + "<br/>Week Evening:" + data[i].endE + "</div>");
}
});
}
so when a user clicks a button, it fire the sorting function..Sadly it doesn't work..Placing the function within success, doesn't perform search function it was doing earlier without any sort. Even if I placed it outside the function , still doesn't work.
To sort an array, you can use Array.prototype.sort.
Without any arguments, it attempts to sort elements alphabetically, but you can pass in a comparing function instead.
The function will receive two arguments and should return less than 0, 0 or greater than 0 to define where argument 1 should be in relation to argument 2.
Your sorting function should look something like this:
data.responseData.sort(function (a, b) {
switch (sortOption) {
case 1:
a = a.name,
b = b.name;
type = "string";
case 2:
a = a.reputation,
b = b.reputation;
type = "numeric";
// etc
}
if (type == "numeric")
{
// numeric comparison
return a > b ? 1 : (a < b ? -1 : 0);
} else if (type == "string") {
// string comparison
return a.localeCompare(b);
}
// etc
return;
});
localeCompare will compare the strings for you :)

Categories