I have a variable tokens which is used as an OTP.It is also stored in the Session variable. I want that tokens to be accessible in JavaScript. So I created a function to return the variable.
function submitotp() {
var re = new RegExp("^[A-Z]{6}$");
var term = document.getElementById("otpinp").value;
var count = 0;
if (re.test(term)) {
$("#sup2").hide();
$("#sup3").show();
return true;
}
else {
return false;
}
and my returning function is
public string tokens(string token)
{
token = Session["otp"].ToString();
return token;
}
I want to access tokens and check if it matches that of a textbox.
Edit: It is an MVC code.
Put your Session["otp"] into ViewData["otp"] and use it on your view like below
In Controller
ViewData["otp"] = Session["otp"];
In View
#ViewData["otp"]
$.post("#Url.Action("tokens","Citizen")", function (data) {
if (re.test(term) && term == data) {
$("#sup2").hide();
$("#sup3").show();
return true;
}
Used this to access the variable. It worked.
Related
I have something like the following:
$('#country1').change(function() {
var hrc = "Yes";
if (className == "HR") {
var hrc = "Yes";
return true;
} else {
var hrc = "No";
return false;
}
Then I am pulling this with JSON into a SP List like:
$('.submitdataAccounts').on('click', function() {
var data = {
__metadata: {
'type': 'SP.Data.ChangeOfAddressListListItem'
},
"high_risk_country": hrc,
};
This part works correctly as everything else in the form posts successfully into the list
If I leave it as a static variable at the top of the page it passes correctly but does not work if it's based on the fuction.
Thanks,
Declare the variable outside the functions, so it is a global variable, and then you can acces it everywhere in your code. If you give a global variable an another value, it is redefined and gets that value until an another value change.
I'm new to JavaScript so I apologize if this is simple. I'm passing a couple values to my controller but after, I need to reset the global variables without refreshing the page. My code looks like this:
var userName = null;
var _delegated = false;
function setAddtionalData(value) {
if(value == true) {
userName = "something";
_delegated = value;
}
}
function getAdditionalData() {
return {
username: userName,
delegated: _delegated
};
userName = null; // Does not get hit
_delegated = false; // Does not get hit
}
But variables never get updated. Is there a way to set these without page a refresh?
Code after the return will not be executed. You need to grab the values, clear the variables, and return the grabbed values:
function getAdditionalData() {
var retval = {
username: userName,
delegated: _delegated
};
userName = null;
_delegated = false;
return retval;
}
Those values are never reached since your return statement exits out of the function.
You should save, username and _delegated to temporary variables, set them to null, and then return the object.
return statements are used to exit out of a function, so anything you put after your return statement will not happen.
JS Function
I write a function to check if user in sharepoint group in javascript
function IsCurrentUserMemberOfGroup(groupName, OnComplete) {
var currentContext = new SP.ClientContext.get_current();
var currentWeb = currentContext.get_web();
var currentUser = currentContext.get_web().get_currentUser();
currentContext.load(currentUser);
var allGroups = currentWeb.get_siteGroups();
currentContext.load(allGroups);
currentContext.load(allGroups, 'Include(Users)');
currentContext.executeQueryAsync(OnSuccess, OnFailure);
function OnSuccess(sender, args) {
var userInGroup = false;
var groupEnumerator = allGroups.getEnumerator();
while (groupEnumerator.moveNext()) {
var oGroup = groupEnumerator.get_current();
if (groupName == oGroup.get_title()) {
var allUsers = oGroup.get_users();
var userEnumerator = allUsers.getEnumerator();
while (userEnumerator.moveNext()) {
var oUser = userEnumerator.get_current();
if (oUser.get_id() == currentUser.get_id()) {
userInGroup = true;
break;
}
}
}
}
OnComplete(userInGroup);
}
function OnFailure(sender, args) {
OnComplete(false);
} }
Usage
I use it in another function, wish to get the bool value of OnComplete and return it.
function SetButtonPermission() {
var isInGroup;
IsCurrentUserMemberOfGroup("Global", function(isCurrentUserInGroup) {
isInGroup = isCurrentUserInGroup;
});
return isInGroup; }
Question
It seems like I cannot get the bool isCurrentUserInGroup because it alert "isInGroup is undetified".
So How Can I Get The bool value ?
Similar to the answer provided here, when you're dealing with asynchronous function calls and callbacks, you'll be better off injecting data/logic into your callback function instead of returning data out from it.
The alternative is to push the "return" data into a global variable, or at least to a variable accessible within the same scope as the callback's execution, and delay execution of dependent logic until after the callback has executed.
You might want to look into JavaScript promises to see how script authors typically handle asynchronous code.
I have the following object that constructs a session variable:
var sessionObject = function (key) {
this._key = key;
this._content;
this.set = function (v) {
this.setLocal(v);
$.post('/Program/SetVariable',
{ key: this._key, value: v }, function (data) {
});
};
this.get = function (callback) {
var setterCallback = this.setLocal;
$.get('/Program/GetVariable',
{ key: this._key }, function (data) {
setterCallback(data);
}).done(function () {
callback();
});
};
this.setLocal = function (v) {
this._content = v;
};
this.getLocal = function () {
return this._content;
};
}
And my C# in the controller is as follows:
public ActionResult SetVariable(string key, string value)
{
Session[key] = value;
return this.Json(new { success = true });
}
public ActionResult GetVariable(string key)
{
return this.Json(Session[key], JsonRequestBehavior.AllowGet);
}
I create a new session object every time the page is loaded, which references items in the session located on the server. When the session is set with the set() function, _content is set correctly and is able to be accessed publicly through item.getLocal() (either in the browser console or in code).
When I revisit the page and the session object referring to said item is already created, when I run the item.get() function it accesses the session variable and sets it to the _content object, I know this because I can do a console.log(this._content) in the setLocal() function which shows that the variable has been set correctly. But when I wish to access the content of the session object via either this.getLocal() or item._content while through the browser console or other lines of the code I get undefined returned to me.
So to illuminate the process some more this is what I do on a reload where there is already data in the session:
var item = new sessionObject("item");
item.get(printData);
function printData() {
$("printbox").append(item.getLocal());
}
This does not print anything.
Is there a reason I can not access this item's content unless it is specifically set by the item.set function?
Because you do this:
var setterCallback = this.setLocal;
and call it like so:
setterCallback(data);
You have lost the context of your sessionObject instance, so the this inside the setLocal function is no longer your object instance but the global window object.
You can do two things to correct this, save a reference to this instead of saving a reference to the function and call setLocal from that reference
var that = this;
/.../
that.setLocal(data);
or you can bind object instance when you save the setLocal reference
var setterCallack = this.setLocal.bind(this);
I have a json object retrieved from server in my $(document).ready(...); that has an string that I would like to resolve to a function also defined within $(document).ready(...); so, for example:
$(document).ready(function{
$.getJSON(/*blah*/,function(data){/*more blah*/});
function doAdd(left,right) {
return left+right;
}
function doSub(left,right) {
return left-right;
}
});
with json string:
{"doAdd":{"left":10,"right":20}}
One way I thought about was creating an associative array of the function before loading the json:
var assocArray=...;
assocArray['doAdd'] = doAdd;
assocArray['doSub'] = doSub;
Using eval or window[](); are no good as the function may not be called for some time, basically I want to link/resolve but not execute yet.
Change your JSON to
{method: "doAdd", parameters : {"left":10,"right":20}}
Then do
var method = eval(json.method);
// This doesn't call it. Just gets the pointer
Or (haven't tried this)
var method = this[json.method]
How about something like this?
$(function(){
// Function to be called at later date
var ressolvedFunc = null;
// Ajax call
$.getJSON(/*blah*/,function(data){
// Generate one function from another
ressolvedFunc = (function(data) {
var innerFunc;
var left = data.left;
var right = data.right;
// Detect action
for (action in data) {
if (action == "doAdd")
innerFunc = function() {
return left + right;
};
else
innerFunc = function() {
return left - right;
};
}
return innerFunc;
})(data);
});
});
The anonymous function returns fresh function, with the new values stored within the enclosure. This should allow you to call the function at later date with the data previously retrieved from the GET request.
Rich
try this:
var doX = (function() {
var
data = [],
getDo = function(action) {
for(var d in data) {
if (data[d][action]) {
return data[d];
}
}
return null;
};
return {
set: function(sdata) {
data.push(sdata);
},
doAdd: function() {
var add = getDo("doAdd");
if (!add)
return 0;
return add.doAdd.left + add.doAdd.right;
},
doSub: function() {
var sub = getDo("doSub");
if (!sub)
return 0;
return sub.doAdd.left + sub.doAdd.right;
}
};
})();
$(document).ready(function{
$.getJSON(/*blah*/,function(data){ doX.set(data); });
});