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.
Related
Below is code of javascript. I want my checkboxes are selected based on coma seperated values from database. please let me know where i am mistaken
function GetStatesList() {
debugger;
var makeList = [];
var url = '/IAAISettings/GetStatesList';
$.ajax({
type: 'POST',
url: url,
success: function(stateList) {
var makeChkList = ""
for (var i = 0; i < stateList.length; i++) {
var st = stateList[i];
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + stateList[i] + "\" name=\"State_" + stateList[i] + "\" checked=\"" + #Model.States.Contains("Alaska") ? "checked" + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
document.getElementById('StateschkList').innerHTML = makeChkList;
},
error: function(r) {
OnFailure(r);
},
failure: function(r) {
OnFailure(r);
}
});
}
I found issue. because of js is client side and model loads before js load it was not getting modal value and to get value we have to use this line
#Html.Raw(Json.Encode(Model.States));
function GetStatesList() {
debugger;
var arrstates = [];
var url = '/IAAISettings/GetStatesList';
$.ajax({
type: 'POST',
url: url,
success: function (stateList) {
var makeChkList = ""
var st =#Html.Raw(Json.Encode(Model.States));
arrstates = st.split(",");
console.log(st);
for (var i = 0; i < stateList.length; i++) {
var str = stateList[i];
if (arrstates.includes(stateList[i])) {
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + stateList[i] + "\" name=\"State_" + stateList[i] + "\" checked=checked\"" + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
else {
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + i + "\" name=\"State_" + i + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
}
document.getElementById('StateschkList').innerHTML = makeChkList;
},
error: function (r) {
OnFailure(r);
},
failure: function (r) {
OnFailure(r);
}
});
}
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 = [];
}
I need to add a list of task after to click one row in a html table I'm using knockout js. the problem is that I'm just adding de last task from my data in a row and I need to add a new TR inside my element "$taskSelected" for each task. Here is my code
self.retrieveTask = function(data, event) {
if (event.type=="click") {
var id = data.Id;
var $taskSelected = event.currentTarget.parentElement.nextElementSibling;
$.get("#Url.Action("Method", "Controller")", { id: id })
.done(function(data) {
$.each(data, function(key, value) {
var html = "<tr><td>" +
"</td>" +
"<td>" +
" <div >" +
+ value.Type +
"</div> " +
"</td>" +
"<td>" +
" <div >" +
value.Id +
"</div> " +
"</td>" +
"</tr>";
$taskSelected.innerHTML=html;
});
}).fail(function() {
alert("error");
});
};
}
the var $taskSelected contains another row "<tr> </tr>" basically Ii want to nested rows. Some advises please
Try this:
self.retrieveTask = function(data, event) {
if (event.type=="click") {
var id = data.Id;
var $taskSelected = event.currentTarget.parentElement.nextElementSibling;
$.get("#Url.Action("Method", "Controller")", { id: id })
.done(function(data) {
var html = "";
$.each(data, function(key, value) {
html += "<tr><td>" +
"</td>" +
"<td>" +
" <div >" +
+ value.Type +
"</div> " +
"</td>" +
"<td>" +
" <div >" +
value.Id +
"</div> " +
"</td>" +
"</tr>";
});
$taskSelected.innerHTML=html;
}).fail(function() {
alert("error");
});
};
}
All I did was move var html outside of your each loop. This makes sure that all your previous HTML stays inside the variable, otherwise you are overwriting html each time you run through the loop (This is why you're only outputting the last one ;) ).
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;
});
I have a HTML code that extracts variables from JSON as :
<textarea id="{{textarea_id}}" class="comment-insert-text" style = "border: 1px solid #e1e1e1"></textarea>
</div>
<div id="{{btn_id}}" style = "margin: 2px 2px 0 0;width:26px;height: 25px;"class="comment-post-btn-wrapper">
C
</div>
The variables for id are also stored in a hidden temporary variable as:
I want to resolve these variables into a javascript file which executes an onclick function. The function takes in the id variable which is not always static. This dynamic variables are the one, passed to the temporary variable through JSON :
$(document).ready(function() {
$(document).on("click",<id-name to be resolved here> , function() {
alert("yes");
comment_post_btn_click();
});
$(document).on("click", "#comm_first_1", function() {
$('.comment-insert-text').css('border', '1px solid #e1e1e1 ');
});
});
function comment_post_btn_click()
{
var _tt = $('#textarea_id').val();
alert("in");
//Text within the textarea which the person has entered
var _comment = $('<id-name variable>').val();
var _Userid = 1;
// Hard coded the name, should be a session name like $('#Userid').val()
var _Username = "Username_sagar";
// Hard coded the name, should be a session name like $('#Username').val()
if (_comment.length > 0)
{
// proceed with ajax callback
$("#comm_first_1").css('border', '1px solid #e1e1e1');
$.post("comment_insert.php",
{
task: "comment_insert",
Userid: _Userid,
comment: _comment
}
)
.error(
function()
{
console.log("Error: ");
}
)
.success(
function(data)
{
//sucess
//insert html into the ul/li
comment_insert(jQuery.parseJSON(data)); // converts the text which we receive into a javascript object
console.log("ResponseText: " + data);
}
);
console.log(_comment + "Username: " + _Username + "Userid: " + _Userid);
}
else
{
// the textarea is empty, put a border on it
$('.comment-insert-text').css('border', '1px solid #ff0000');
console.log("The textarea is empty");
}
//remove the textarea and ready for another comment
$('#comm_first_1').val("");
}
function comment_insert(data) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
You can just add the click event to the class, not the id, then pass the this object to the function.
$(document).ready(function() {
$(".comment-insert-text").click(function() {
alert("yes");
comment_post_btn_click(this);
});
$(document).on("click", "#comm_first_1", function() {
$('.comment-insert-text').css('border', '1px solid #e1e1e1 ');
});
});
function comment_post_btn_click(textArea)
{
var _tt = $('#textarea_id').val();
alert("in");
//Text within the textarea which the person has entered
var _comment = $(textArea).val();
var _Userid = 1;
// Hard coded the name, should be a session name like $('#Userid').val()
var _Username = "Username_sagar";
// Hard coded the name, should be a session name like $('#Username').val()
if (_comment.length > 0)
{
// proceed with ajax callback
$("#comm_first_1").css('border', '1px solid #e1e1e1');
$.post("comment_insert.php",
{
task: "comment_insert",
Userid: _Userid,
comment: _comment
}
)
.error(
function()
{
console.log("Error: ");
}
)
.success(
function(data)
{
//sucess
//insert html into the ul/li
comment_insert(jQuery.parseJSON(data)); // converts the text which we receive into a javascript object
console.log("ResponseText: " + data);
}
);
console.log(_comment + "Username: " + _Username + "Userid: " + _Userid);
}
else
{
// the textarea is empty, put a border on it
$('.comment-insert-text').css('border', '1px solid #ff0000');
console.log("The textarea is empty");
}
//remove the textarea and ready for another comment
$('#comm_first_1').val("");
}
function comment_insert(data) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}