I have written JavaScript which retrieves data and sets it into a series of tables as shown below.
$(function()
{
$.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'9BBF789F-E5BA-449D-A595-BAA326E2C8FF')/Items?$expand=Category&$select=Id,Related_x0020_Working_x0020_PracId,Title,Reference,Policy_x0020_Type,Category/Title&$orderby=Category/Title asc",
type:"get",
headers: { "accept": "application/json;odata=verbose" },
success: function(dataObj)
{
//to uniquely identifiy the accordion.
var intCat = 0;
var arrPolicies = [];
var arrCategories = [];
//Get the policies and seperate out the categories from the returned REST call
for(var i =0; i < dataObj.d.results.length; i++)
{
var strCategory = dataObj.d.results[i].Category.Title;
arrPolicies.push({
"Id" : dataObj.d.results[i].Id,
"Title" : dataObj.d.results[i].Title,
"Category" : strCategory,
"Ref" : dataObj.d.results[i].Reference,
"PolicyType" : dataObj.d.results[i].Policy_x0020_Type,
"WorkingPracticeId" : dataObj.d.results[i].Related_x0020_Working_x0020_PracId
});
//setting category if not found
//in array
if(arrCategories.indexOf(strCategory) == -1)
{
//Add the category to the list...
arrCategories.push(strCategory);
}
}
//Output the menu to the screen for each category - one by one
arrCategories.forEach(function(varCategory)
{
var strCatIdentifier = "tblCategory_" + intCat;
var strCatImgIdentifier = "tblCategory_image_" + intCat;
var strCategoryInfo = "<table>"+
"<tbody>" +
"<tr>"+
"<td class='category'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatIdentifier + ","+strCatImgIdentifier+")'>"+
"<img id='"+strCatImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand category'/>"+
"</a> "+
varCategory +
"</td>"+
"</tr>"+
"<tr><td>"+
"<table id='" + strCatIdentifier + "' class='indent hidden'>";
//looping through policies - add the details into the category table's cell
arrPolicies.forEach(function(varPolicy)
{
//checking the category attached to the policy is the same as what
//category it is on
if(varPolicy.Category == varCategory)
{
//checking to see if the
if(varPolicy.PolicyType == "Policy and Responsibility")
{
strCategoryInfo += "<tr>"+
"<td class='policy'>" +
"<a href='#'>"+
"<img src='"+_spPageContextInfo.webAbsoluteUrl+"/SiteAssets/Images/arrowicon.png' alt='View Document'/>"+
"</a>"
+ varPolicy.PolicyType + ": "+varPolicy.Ref +" - " + varPolicy.Title +
"</td>"+
"</tr>";
}
//If Working Practice - add in the sub-table (3rd level table) for attachments
if(varPolicy.PolicyType == "Working Practices")
{
var strCatWPIdentifier = "tblWorkingPractice" + varPolicy.Id;
var strCatWPImgIdentifier = "sub_level_image" + varPolicy.Id;
strCategoryInfo += "<tr>"+
"<td class='working_practice'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatWPIdentifier + ","+strCatWPImgIdentifier+")'>"+
"<img id='"+strCatWPImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand working practice'/>"+
"</a> "+
varPolicy.PolicyType + " - " + varPolicy.Title+
"</td>"+
"</tr>";
var intAttachmentCount = 0;
//Build a table by looping through the policies array AGAIN and only use the policies where the Policy Type is 'Attachment' AND the 'WorkingPracticeID' is the same as the pilocy ID
arrPolicies.forEach(function(varWPAttachment)
{
if(varWPAttachment.WorkingPracticeId == varPolicy.Id && varWPAttachment.PolicyType == "Working Practice Attachment")
{
intAttachmentCount++;
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
varWPAttachment.PolicyType +" - "+ varWPAttachment.Title+ " - " + varPolicy.Title+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
});
if(intAttachmentCount == 0)
{
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
"Sorry, no attachments found for this practice."+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
}
}
});
//Close the 'Category details' table
strCategoryInfo += "</table>";
//Close the table for the category...
strCategoryInfo += "</td></tr>" +
"</tbody>"+
"</table>";
intCat++;
$('#divQualityFrameworkMenu').append(strCategoryInfo + "<br />");
});
},
error: function(error)
{
alert("Error");
}
});
});
I want to be able to organise them so that related data is grouped together ie Policies are above working practices.
How would I go about doing this
This seems pretty easy. After the first for (var d = 0; [...] ) loop, but before the arrCategories.forEach([...]), just sort arrPolicies to your choosing:
arrPolicies.sort(function(policy1, policy2) {
//Policies BEFORE Working Practicies:
if (policy1.PolicyType === "Policies and Responsibilities" && policy2.PolicyType === "Working Practices") {
return -1;
}
//Working Practicies AFTER Policies:
if (policy1.PolicyType === "Working Practices" && policy2.PolicyType === "Policies and Responsibilities") {
return 1;
}
//[Include any other orderings you might have...]
//If you've reached the end here, then you must not care about the ordering of these policies, so just make them "equal":
return 0;
});
Related
I am trying to complete my code that dynamically produces a table using Jquery DataTables plugin.
The code works up to a point, it displays the data but above the data it also displays "No data available in table".
From what I have read it is something to do with the table initialisation, Can anyone see where I am going wrong.
$(document).ready(function(){
$('#userTable').DataTable( {
"ordering": false,
paging: false,
searching: false,
language: {
emptyTable: "No data available in table", //
loadingRecords: "Please wait .. ", // default Loading...
zeroRecords: "No matching records found"
},
"stripeClasses": [ 'odd-row', 'even-row' ]
});
$.ajax({
url: 'server_processing.php',
type: 'get',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var recordid = response[i].RecordID;
var deviceid = response[i].DeviceID;
var mediatype = response[i].MediaType;
var screenlocation = response[i].ScreenLocation;
var promotionname = response[i].PromotionName;
var fromdate = response[i].FromDate;
var fromtime = response[i].FromTime;
var todate = response[i].ToDate;
var totime = response[i].ToTime;
var promotionimage = response[i].PromotionImage;
var orientation = response[i].Orientation;
var enddate = todate +' '+totime;
var startdate = fromdate +' '+fromtime;
var now = new Date();
var nowdate = fixDigit(now.getDay()) + '-' +fixDigit(now.getMonth() + 1) + '-' + now.getFullYear()+' ' +now.getHours() + ":" + now.getMinutes();
// Utility function to prepend zeros to single digits:
function fixDigit(val){
return val.toString().length === 1 ? "0" + val : val;
}
var tr_str = "<tr class='TableText'>" +
"<td style='color:#333;font-size:0.8em;'>" + promotionname + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + deviceid + " " + screenlocation + "</td>" +
"<td align='center' style='color:#333;font-size:0.8em;'>" + orientation + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + promotionimage + "</td>" +
"<td align='center' style='color:#333;font-size:0.8em;'>" + mediatype + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + fromdate + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + todate + "</td>"
if( (new Date(startdate).getTime() > new Date(nowdate).getTime())) {
tr_str += "<td align='center' style='color:#333;font-size:0.8em;' class='Active'>Active</td>";
} else {
tr_str += "<td align='center' style='color:#333;font-size:0.8em;' class='Scheduled'>Scheduled</td>";
}
tr_str += "<td align='center' style='color:#333;font-size:0.8em;'><input type='button' name='edit' value='Edit' id=" + (i+1) + " class='btn btn-info btn-xs btn-block edit_data'></td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
});
Many thanks in advance for you help and time.
This is because you are appending content without deleting previous, "no data" massage is a row, so you should clear it before for loop:
success: function(response){
var len = response.length;
$("#userTable tbody").html("");
for(var i=0; i<len; i++){
var recordid = response[i].RecordID;
var deviceid = response[i].DeviceID;
...
One thing, this is not the best way to insert data in datatables.
One more thing is here that if I use the alert() at end of the ajax code the code is working fine. here whatever the ajax response comes has to be appended to the existing table.
for (var i = 1; i < rows.length; i++) {
var cells = splitCSVtoCells(rows[i], ",");
var obj = {};
for (var j = 0; j < cells.length; j++) {
obj[first_Row_Cells[j]] = cells[j];
}
jsonArray.push(obj);
}
console.log(jsonArray);for (var i = 0; i < jsonArray.length-1; i++) {
html += "<tr id=\"rowitem" + i + "\"><td id=\"rownum"+i+ "\" style=\"display:none;\">" + i + "</td><td> " + jsonArray[i].Clientgroup + " </td>";
html += "<td>" + jsonArray[i].hostgroup + "</td>";
html += "<td>" + jsonArray[i].server + "</td>";
html += "<td>" + jsonArray[i].Group + "</td>";
html += "<td>" + jsonArray[i].user + "</td>";
html += "<td>" + jsonArray[i].ticket + "</td>";
html += "<td>" + jsonArray[i].requesttype + "</td>";
$.ajax({
url : "BulkValidateServlet",
type : "POST",
data : {clientgroup: jsonArray[i].Clientgroup, hostgroup: jsonArray[i].hostgroup, server: jsonArray[i].server
},success : function(response){
//alert("i in of ajax:"+i);
status = response;
if (status) {
//alert("outside if: " + status);
//$('<img src=\'images/check_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/check_mark.png' height='20' width='20'/></td>";
} else {
//alert("outside else: " + status);
//$('<img src=\'images/cross_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/cross_mark.png' height='20' width='20'/></td>";
}
console.log("Data: " + status);
// alert("Data: " + status );
//return status;
}
});
console.log("outside: " + status);
alert();
}
document.getElementById('tbodyLeads').innerHTML = html;
}
You can try adding
async: false
to your ajax attributes.
Refer to this link.
I'm getting the following error in my javascript. As the title states, this code is working on my localhost, but not when I put it onto my server
Uncaught TypeError: Cannot read property 'push' of null
at addItemToCart (shoppingCart.js:36)
at HTMLButtonElement.<anonymous> (shoppingCart.js:193)
at HTMLDocument.dispatch (jquery-1.11.1.min.js:3)
at HTMLDocument.r.handle (jquery-1.11.1.min.js:3)
I have identified that just before this push function is called that the cart variable is indeed null, but I declare it globally as an empty array, so I'm not sure why that would be.
Code for the function its failing on
var cart = [];
function addItemToCart(name, price, count, id, shortName) {
for (var i in cart) {
if (cart[i].id === id) {
cart[i].count += count;
saveCart();
for (var i in cart) {
if (cart[i].id == 500 && id != 500) {
removeItemFromCart(500);
alert('because you changed your cart, you will have to reapply your coupon');
}
}
return;
}
}
for (var i in cart) {
if (cart[i].id == 500 && id != 500) {
removeItemFromCart(500);
alert('because you changed your cart, you will have to reapply your coupon');
}
}
var item = new Item(name, price, count, id, shortName);
console.log(cart);
cart.push(item);
saveCart();
}
The error happens at teh cart.push(item); line because cart is null and can not be pushed to. Anymore information someone may need to help feel free and I will shoot it your way.
Thanks in advance!!!
edit:
function displayCart() {
console.log("*** display Cart ***");
var cartArray = listCart();
var output = "<tr><th>Items</th><th>Quantity</th><th>Price</th></tr>";
var output2 = "<tr><th> </th><th>Product name</th><th>Product price</th><th>Quantity</th><th>Total</th></tr>";
var output3 = " <tr><th>Product(s)</th></tr>";
var output4 = "";
console.log(listCart());
for (var i in cartArray) {
output += "<tr class='item'><td><div class='delete' id='removeItem' data-id='" + cartArray[i].id + "'></div>" + cartArray[i].name + "</td><td><input type='text' value='" + cartArray[i].count + "' readonly></td> <td class='price'>" + cartArray[i].price + "</td></tr>"
output2 += "<tr class='item'>"
+ "<td class='thumb'><a href='" + cartArray[i].id + "-item.php'><img src='img/catalog/product-gallery/" + cartArray[i].id + ".png' alt='Product Image'/></a></td>"
+ "<td class='name'><a href='" + cartArray[i].id + "'-item.php'>" + cartArray[i].name + "</a></td>"
+ "<td class='price'>$" + cartArray[i].price + "</td>"
+ "<td class='qnt-count'>"
+ "<a class='incr-btn' href='#' id='oneless' data-id='" + cartArray[i].id + "'>-</a>"
+ "<input class='quantity form-control' type='text' value=' " + cartArray[i].count + " '>"
+ "<a class='incr-btn' id='onemore' data-productid='" + cartArray[i].id + "' data-name='" + cartArray[i].name + "' data-quantity='" + cartArray[i].count + "' href='#'>+</a>"
+ "</td>"
+ "<td class='total'>$<em id='test'>" + cartArray[i].total + "</em></td>"
+ "<td class='delete' id='removeAllFromCart' data-id='" + cartArray[i].id + "'><i class='icon-delete'></i></td>"
+ "</tr>";
output3 += " <tr><td class='name border'>" + cartArray[i].shortName + "<span>x" + cartArray[i].count + "</span></td>"
+ "<td class='price border'>$" + cartArray[i].total + "</td></tr>";
if ($("#offerCount").attr("data-id") == cartArray[i].id) {
output4 += +"<a class='incr-btn' href='#' id='oneless' data-id='" + cartArray[i].id + "'>-</a>"
+ "<input class='quantity form-control' type='text' value=' " + cartArray[i].count + " '>"
+ "<a class='incr-btn' id='onemore' data-productid='" + cartArray[i].id + "' data-name='" + cartArray[i].name + "' data-quantity='" + cartArray[i].count + "' href='#'>+</a>";
}
}
output3 += " <tr><td class='th border'>Shipping</td><td class='align-r border'>Free shipping</td></tr>"
+ "<tr><td class='th'>Order total</td><td class='price'>$" + totalCart() + "</td></tr>"
$("#offerCount").html(output4);
$("#productDisplay").html(output3);
$("#showFullCart").html(output2);
$("#showCart").html(output);
$("#cartTotal").html(totalCart());
$("#totalCart").html(totalCart());
$("#myCartTotal").html(totalCart());
$("#showmyTotal").html(totalCart());
$("#cartCount").html(countCart());
}
function addCouponToCart(coupon) {
if (coupon == 'coupon10' && couponsAdded == 0) {
var couponReduce = -(totalCart() * .1).toFixed(2);
addItemToCart('10% off Coupon', couponReduce, 1, 500, '10% off');
couponsAdded += 1;
saveCoupon();
}
displayCart();
}
function countCart() {
var totalCount = 0;
for (var i in cart) {
totalCount += cart[i].count;
}
return totalCount;
}
function removeItemFromCartAll(id) {
for (var i in cart) {
if (cart[i].id === id) {
cart.splice(i, 1);
break;
}
}
for (var i in cart) {
if (cart[i].id == 500 && id != 500) {
removeItemFromCart(500);
alert('because you changed your cart, you will have to reapply your coupon');
}
}
saveCart();
}
Code that calls the addCouponToCart Function whenever a post gets set.
<?php if (isset($_POST['coupon_code'])) { ?>
<script>
addCouponToCart(coupon);
</script>
<?php } ?>
#codenoname Provided the correct answer of checking for the null cart. That solved the issue, ultimately a lot of functions were not being defined properly. I had wrapped the entire code in a document ready function which seemed to be the issue. Whenever I removed that it worked. Thank you all for your input.
if (!cart) {
cart = [];
}
Im making a site but i want to check the value of a session so i can show a button depending on what the users role is.
the problem im having is that i cant get the value of the session into SessionValue
i will also add that the file is a .js
what i have so far:
function getGroups() {
var SessionValue = <?php print($_SESSION['user_role']); ?>;
$.ajax({
url: 'services/functions.php',
data: {
action: 'getGroups'
},
type: 'post',
success: function (output) {
var result = JSON.parse(output);
result = result.results;
$(result).each(function (index, element) {
var out = "<div class='row'>";
out += "<div class='col-md-3'>";
out += "<img class='img-responsive image_" + index + "' src=" + element.group_image + ">";
out += "</div>";
out += "<div class='col-md-9'>";
out += "<h3>" + element.group_title + "</h3>";
if(SessionValue == "admin"){
out += "<button class='btn btn-primary pull-right' type='button' id='submitPost'>Delete</button>";
}
out += "<h4 class='hidden_" + index + "'>" + moment(element.group_playdate, 'HH:mm:ss').format('HH:mm') + "</h4>";
out += "<p class='hidden_" + index + "'>" + element.group_description + "</p>";
out += "</div>";
out += "</div>";
out += "<hr/>";
$(".groupContainer").append(out);
$(".hidden_" + index).hide();
$(".image_" + index).hover(
function () {
$('.hidden_' + index).fadeIn(200);
},
function () {
$('.hidden_' + index).fadeOut(100);
}
);
});
},
error: function (output) {
console.error("Something went wrong while loading the groups from the database.");
}
});
}
the session is started and the user_role is also defined #login.
I'm using Facebook Javascript SDK and FB.api. I read public pages' posts and wanted to show it on my website. So I made the call with FB.api and got the response. But while I try to show them by Facebook Embed System it just didn't show up.
Here is my code
FB.api("/" + PageId + "/posts",
{
access_token: getCookie("access_token"),
since: From,
until: To,
fields: "id,likes.summary(true).limit(0),comments.summary(true).limit(0),shares,link",
limit: LoadLimit,
date_format: "U",
},
function (res) {
$("#load_post").attr("disabled", false).attr("value", "Load Posts");
if (typeof res.error === 'undefined') {
if (res.data.length > 0) {
for (var i = 1; i <= res.data.length; i++) {
var NewData = res.data[i - 1];
var Id = NewData.id.split("_")[1];
var CreatedTime = NewData.created_time;
var Likes = NewData.likes.summary.total_count;
var Comment = NewData.comments.summary.total_count;
var Share = 0;
var Link = NewData.link;
if (typeof NewData.shares !== 'undefined') {
Share = NewData.shares.count;
}
var Data = "";
Data += "<tr>";
Data += "<td>" + i + "</td>";
Data += "<td><div id='" + Id + "' class='fb-post' data-href='" + Link + "' data-width='350'></div></td>";
Data += "<td>" + CreatedTime + "</td>";
Data += "<td>" + Likes + "</td>";
Data += "<td>" + Comment + "</td>";
Data += "<td>" + Share + "</td>";
Data += "<td></td>";
Data += "<td></td>";
Data += "<td></td>";
Data += "</tr>";
$("#data_area").append(Data);
FB.XFBML.parse(document.getElementById(Id));
}
} else {
alert("No data found.");
}
} else {
alert("Error occured.\n" + res.error.message);
}
});
Even I tried "FB.XFBML.parse" but lately checking the documentation I found that it has no effect on Embed Post.
I checked the console and found no error or something.
Please help me out.