I have a piece of code which is intended to check the permission level and group membership of a use and launch a dialog box if the user has the correct permissions to access that section of the site.
function bindSettingsButton() {
$("#mt-ngw-personalsettings").on("click", function() {
RequestNewSite();
});
}
function RequestNewSite() {
var HasPermission = false;
var isGroupMember = false;
CheckCurrentUserMembership();
CheckUserHasEditPermissions();
CheckUserPermissions();
}
function CheckCurrentUserMembership() {
var clientContext = new SP.ClientContext.get_current();
this.currentUser = clientContext.get_web().get_currentUser();
clientContext.load(this.currentUser);
this.userGroups = this.currentUser.get_groups();
clientContext.load(this.userGroups);
clientContext.executeQueryAsync(OnQuerySucceeded, OnQueryFailed);
}
function OnQuerySucceeded() {
var isMember = false;
var groupsEnumerator = userGroups.getEnumerator();
while (groupsEnumerator.moveNext()) {
var group = groupsEnumerator.get_current();
if(group.get_title() == "Create Site OptOut") {
isMember = true;
this.isGroupMember = true;
break;
}
}
}
function OnQueryFailed()
{
alert("Couldn't check user group membership. Please contact to resolve this issue.");
}
function CheckUserHasEditPermissions() {
context = new SP.ClientContext.get_current();
web = context.get_web();
this._currentUser = web.get_currentUser();
this._theList = web.get_lists().getByTitle('siterequests');
context.load(this._currentUser);
context.load(this._theList, 'EffectiveBasePermissions')
context.executeQueryAsync(Function.createDelegate(this, this.onPermissionsSuccessMethod), Function.createDelegate(this, this.onPermissionsFailureMethod));
}
function onPermissionsSuccessMethod(sender, args) {
if (this._theList.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems))
{
this.HasPermission = true;
}
else
{
this.HasPermission = false;
}
}
function onPermissionsFailureMethod()
{
alert("Couldn't check permissions. Please contact to resolve this issue.");
}
function CheckUserPermissions() {
if(this.isGroupMember == true)
{
alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact .");
}
else if(this.HasPermission == false)
{
alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact .");
}
else
{
showDialogue();
document.getElementById("next-stage").focus();
}
}
Unfortunately when it reaches the end this section the variables HasPermission and isGroupMember are still undefined so the dialogue launches automatically for every user.
I have a feeling I have misused the .this keywords and this is a scoping error but I am not expert enough in JS to know for certain or be able to fix it. Can anyone tell me exactly what I've done wrong and how to fix it please?
You are performing async functions, which means the rest of the code will keep executing even though the stuff you have started first are not completed yet.
You will have to call the CheckUserPermissions after onPermissionsSuccessMethod and the OnQuerySucceeded function has completed.
In addition to this the HasPermission and isGroupMember variables are local to the RequestNewSite function, which means they are out of the scope of the CheckUserPermissions function.
var HasPermission = false;
var isGroupMember = false;
var CompletedCallbacks = 0;
function bindSettingsButton() {
$("#mt-ngw-personalsettings").on("click", function() {
RequestNewSite();
});
}
function RequestNewSite() {
CheckCurrentUserMembership();
CheckUserHasEditPermissions();
}
function CheckCurrentUserMembership() {
var clientContext = new SP.ClientContext.get_current();
this.currentUser = clientContext.get_web().get_currentUser();
clientContext.load(this.currentUser);
this.userGroups = this.currentUser.get_groups();
clientContext.load(this.userGroups);
clientContext.executeQueryAsync(OnQuerySucceeded, OnQueryFailed);
}
function OnQuerySucceeded() {
var isMember = false;
var groupsEnumerator = userGroups.getEnumerator();
while (groupsEnumerator.moveNext()) {
var group = groupsEnumerator.get_current();
if(group.get_title() == "Create Site OptOut") {
isMember = true;
isGroupMember = true;
break;
}
}
CompletedCallbacks++;
CheckUserPermissions();
}
function OnQueryFailed()
{
alert("Couldn't check user group membership. Please contact SPCOE#capita.co.uk to resolve this issue.");
}
function CheckUserHasEditPermissions() {
context = new SP.ClientContext.get_current();
web = context.get_web();
this._currentUser = web.get_currentUser();
this._theList = web.get_lists().getByTitle('siterequests');
context.load(this._currentUser);
context.load(this._theList, 'EffectiveBasePermissions')
context.executeQueryAsync(Function.createDelegate(this, this.onPermissionsSuccessMethod), Function.createDelegate(this, this.onPermissionsFailureMethod));
}
function onPermissionsSuccessMethod(sender, args) {
if (this._theList.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems))
{
HasPermission = true;
}
else
{
HasPermission = false;
}
CompletedCallbacks++;
CheckUserPermissions();
}
function onPermissionsFailureMethod()
{
alert("Couldn't check permissions. Please contact SPCOE#capita.co.uk to resolve this issue.");
}
function CheckUserPermissions() {
if(CompletedCallbacks != 2) return;
if(isGroupMember == true)
{
alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact SPOCOE#capita.co.uk.");
}
else if(HasPermission == false)
{
alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact SPOCOE#capita.co.uk.");
}
else
{
showDialogue();
document.getElementById("next-stage").focus();
}
}
This code should work.
$("#mt-ngw-personalsettings").on("click", function() {
RequestNewSite();
});
If you are expecting to use RequestNewSite as a constructor, you need to use new to allocate it. If you call as a function no object (and thus state) is created.
Additionally all members of the type need to be created explicitly on this.
So
function RequestNewSite() {
var HasPermission = false;
var isGroupMember = false;
CheckCurrentUserMembership();
CheckUserHasEditPermissions();
[...]
Needs to be
function RequestNewSite() {
this.HasPermission = false;
this.isGroupMember = false;
this.CheckCurrentUserMembership();
this.CheckUserHasEditPermissions();
[...]
Related
I have tried to create a login function which when the user enters the vaild name and password then it will print "welcome user " else "invalid user".
In my code it accepts one username and password and showing invalid for another one...I cant understand why its showing like this...
code:
<script>
let userName=document.getElementById("input1");
let mailId=document.getElementById("input2");
var out=[{Name:"dhanam",mail:"dhanamram98#gmail.com"},
{Name:"alamelu",mail:"alamu98#gmail.com"}];
function input()
{
var input=userName.value;
var output=mailId.value;
var created=[{Name:input,mail:output}];
return created
}
function output()
{
var inp=input();
for(var i=0;i<inp.length;i++)
{
for(var j=0;j<out.length;j++)
{
console.log(inp[i].Name+inp[i].mail);
console.log(out[j].Name+out[j].mail);
if((inp[i].Name== out[j].Name)&&
(inp[i].mail==out[j].mail))
{
document.getElementById("out1").innerText="welcome
user";
}
else{
document.getElementById("out1").innerText="Invalid
user";
}
}
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);
</script>
find fiddle here:
https://jsfiddle.net/xp1Lrbdh/#&togetherjs=d0wTznLFgu
The issue is because of the iteration you are doing even after finding if entered user is valid user. In simple terms, putting a break statement solves your problem.
See the snippet below:
let userName=document.getElementById("input1");
let mailId=document.getElementById("input2");
var out=[{Name:"dhanam",mail:"dhanamram98#gmail.com"},
{Name:"alamelu",mail:"alamu98#gmail.com"}];
function input()
{
var input=userName.value;
var output=mailId.value;
var created=[{Name:input,mail:output}];
return created
}
function output()
{
var inp=input();
for(var i=0;i<inp.length;i++)
{
for(var j=0;j<out.length;j++)
{
console.log(inp[i].Name, inp[i].mail);
console.log(out[j].Name, out[j].mail);
if((inp[i].Name== out[j].Name)&&(inp[i].mail==out[j].mail))
{
document.getElementById("out1").innerText="welcome user";
break;
}
else{
document.getElementById("out1").innerText="Invalid user";
}
}
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);
NOTE: This is not a best practice to verify credentials also avoid using var, use let, const instead
const accounts = [
{
name:"dhanam",
mail:"dhanamram98#gmail.com"
},
{
name:"alamelu",
mail:"alamu98#gmail.com"
}
]
function output() {
const nameNode = document.getElementById("input1")
const mailNode = document.getElementById("input2")
const name = nameNode.value
const mail = mailNode.value
const found = accounts.find(a => a.name === name && a.mail === mail)
if (found) {
document.getElementById("out1").innerText="welcome user";
} else {
document.getElementById("out1").innerText="Invalid user";
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);
I need to validate the extension of an uploading file in js.I have successfully created a fuction like as follows.
function FileExtension_Validate(txt)
{
if( !txt.match(/\.(pdf)|(doc)|(PDF)|(DOC)|(docx)|(DOCX)$/)) { return false; } else {return true; }
}
But now my situation is, i have a database field which have data as follows
pdf,doc,PDF,DOC,docx,DOCX
Now i need to create a function based on the data from database.Is there any possible solution.Please help me..?
I solved it as follows..
function FileExtension_Validate(txt)
{
//alert(txt);
var extension=document.getElementById('extension').value;
var piece = extension.split(',');
var split=extension.split(',').length
var flag=0;
//alert(piece[0]);
for (var i = 0; i <split; i++)
{
var test=piece[i];
//alert(test);
if( txt!=test) { flag++;}
//else {return true; }
}
// alert(flag);
if(flag==split)
{
return false;
}
else{
return true;
}
in extension i have passed the extension of the uploade file
I cannot work out how to get the Knockout Validation plugin to validate a custom selection of viewmodel properties. I can call isValid() to validate the entire viewmodel successfully however.
I have followed the documentation set out here which covers the scenario and also checked all the answers I can find on stack overflow.
My code looks like this:
function MyViewModel() {
var self = this;
self.myproperty = ko.observableArray().extend({ minLength: { message: 'You must specify at least one item.'} })
self.anotherproperty = ko.observable().extend({ required: { params: true, message: 'You must supply a value.'} });
self.IsEntireModelValid = function() {
if (!self.isValid()) {
self.errors.showAllMessages();
return false;
}
else {
return true;
}
self.IsAnotherPropertyValidOnly = function() {
var errors = ko.validation.group(self.anotherproperty);
if (errors.length > 0) {
errors.showAllMessages();
return false;
}
else {
return true;
}
}
When I call self.IsAnotherPropertyValidOnly() the errors variable contains no errors, but when I call self.IsEntireModelValid() I get the correct response.
Could someone point out what I'm doing wrong?
You need to use errors().length.
self.IsAnotherPropertyValidOnly = function() {
var errors = ko.validation.group(self.anotherproperty);
if (errors().length > 0) {
errors.showAllMessages();
return false;
}
else {
return true;
}
}
http://jsfiddle.net/WY7V3/2/
I have been looking at this code for too long and just can't see what I am missing. The error states that there is a syntax error on the very last line, I have checked all of my braces but cannot seem to find it. Can anyone help me to find it?
window.addEvent('domready', function() {
// Get the form
var form = $('comments_form');
// if the form is found...
if (form) {
// obtain error fields
var aname = $('accountname');
var anumber = $('accountnumber');
var cname = $('cardname');
var cnumber = $('cardnumber');
var security = $('securitycode');
var zip = $('zipcode');
// Set the default status
var isValid = true;
// input error function for the error messages
var addError = function (field, msg) {
field.addClass('error'); // Add error class to field
var error = field.getParent().getElement('span') || new Element('span', {'class': 'error'}); // add error message if not already placed
error.set('text', msg); // error text msg
error.inject(field, 'after'); // Insert error message after field
};
// detach error function used to delete any error messages and remove the error class
var removeError = function (field) {
field.removeClass('error'); // Remove error class from form fields
var error = field.getParent().getElement('span'); // find any existing error messages
// destroy if error message
if (error) {
error.destroy();
}
};
// insert submit form event
form.addEvent('submit', function (e) {
// Test name length
if (aname.get('value').length === 0) {
isValid = false;
addError(name, accountnameError);
} else {
isValid = true;
removeError(aname);
}
form.addEvent('submit', function (e) {
// Test name length
if (anumber.get('value').length === 0) {
isValid = false;
addError(anumber, accountnumberError);
} else {
isValid = true;
removeError(accountnumber);
}
form.addEvent('submit', function (e) {
// Test name length
if (cname.get('value').length === 0) {
isValid = false;
addError(cname, nameError);
} else {
isValid = true;
removeError(cname);
}
form.addEvent('submit', function (e) {
// Test name length
if (cnumber.get('value').length === 0) {
isValid = false;
addError(cnumber, numberError);
} else {
isValid = true;
removeError(cname);
}
form.addEvent('submit', function (e) {
// Test name length
if (securitycode.get('value').length === 0) {
isValid = false;
addError(securitycode, securityError);
} else {
isValid = true;
removeError(securitycode);
}
form.addEvent('submit', function (e) {
// Test name length
if (zipcode.get('value').length === 0) {
isValid = false;
addError(zipcode, zipError);
} else {
isValid = true;
removeError(zipcode);
}
// If form invalid then stop event happening
if (!isValid) {
e.stop();
}
});
}
});
You're missing the end curly brace and closing paranthesis for each form.addEvent('submit', function (e) {. Also, you could combine them into a single handler. Using a beautifier helps you easily find if these types of syntax errors.
Example for one of them
form.addEvent('submit', function (e) {
// Test name length
if (aname.get('value').length === 0) {
isValid = false;
addError(name, accountnameError);
} else {
isValid = true;
removeError(aname);
}
}); // <- you don't have that
On a side note, your var aname = $('accountname'); (and subsequent lines) look wrong. You probably mean to select it by id; use $('#accountname'). And I'm not aware of any addEvent function. I'm assuming you're using some other library, but for reference with jQuery you should use .on(event, handler)
I am bulding a table that either shows a play button or a stop button. (and some other stuff)
for(var i = 0; i < result.length; i++){
var current = result[i].split("$");
if (CheckRunning(current[0])){
t = t + "<tr><td><img alt='stop' id='img"+i+"' src='stop.png' onclick='ChangeButton(\"img"+i+"\");'/>";
} else {
t = t + "<tr><td><img alt='play' id='img"+i+"' src='play.png' onclick='ChangeButton(\"img"+i+"\");'/>";
}}
The problem here is the CheckRunning method. It opens a database which is an asynchron method. I cant simply do a return true/false. So whats the solution? anyway, here is the code for it:
var tabel;
var running = false;
function CheckRunning(tabel){
this.tabel = "tabel"+tabel+"";
var db = window.openDatabase(this.tabel, "1.0", this.tabel, 1000000);
db.transaction(checkrunningDB, checkerrorCB);
console.log(this.running);
return this.running;
}
function checkrunningDB(tx) {
tx.executeSql('SELECT max(id), sluttime FROM '+this.tabel, [], checkrunningSuccess, checkerrorCB);
}
function checkrunningSuccess(tx, results) {
if (results.rows.item(0).sluttime != null){
this.running = false;
} else{
this.running = true;
}
}
function checkerrorCB(err) {
this.running = false;
console.log(err);
}
Pass a callback function to CheckRunning:
CheckRunning(current[0], function(isRunning){...})
...
function CheckRunning(tabel, callback)
{
var isRunning = null; // we don't know yet
....
callback(isRunning);
}
It's similar to your tx.executeSql function which takes checkRunningSuccess as a callback. In that case the function name is hard coded as checkRunningSuccess, you could do the same in checkRunning.
By the way, if this is a public webapp running SQL queries makes you vulnerable to SQL injection attacks.