doPostback Error - javascript

I am trying to execute a javascript function on page load and then do a postback that would call a function in code behind. I am getting time zone data and trying to pass them as arguments to __dopostback. Here is what I have (abbreviated):
in .aspx file
<body onload="GetLocalTime()">
....
function GetLocalTime(){debugger
var d = new Date();
var tzOffset = d.getTimezoneOffset();
var hfOffset = document.getElementById('<%=hfOffset.ClientID%>');
var hfTZName = document.getElementById('<%=hfTZName.ClientID%>');
var tzName = getTimezoneName();
hfOffset.value = tzOffset;
hfTZName.value = tzName;
__doPostBack('TZSessionVars', tzOffset, tzName);
}
In code behind's Page_Load(), if IsPostback is true:
string sTarget = Request["__EVENTTARGET"];
if (sTarget.Equals("TZSessionVars"))
{
string sArg = Request["__EVENTARGUMENT"];
SetTZSessionVars(sArg); // this is where I parse the argument and set session vars
}
When I trace the javascript, when it hits __doPostback, it says:Microsoft JScript runtime error: Object expected
The parameters tzOffset and tzName are OK and have valid values.

You can use the __EVENTARGUMENT as explained in this article.
Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net
Try passing concatenated values as a single __EVENTARGUMENT and split it at server to get actual arguments

Related

How do I pass a variable from .js page into a .aspx page and have it available to me in an .aspx.js page?

I'm new to ASP and I am trying to pass a variable into a .aspx.js page so I can use it in an if statement to determine whether or not something should be displayed.
I have a .js page that calls a method which I have added a variable to:
if(strStatus == 4 || strStatus == 7) {
LMS_Roster_WaivedNotes(strStatus);
}
The method called is as follows which I have added the parameter for status
function LMS_Roster_WaivedNotes(strStatus) {
var strWindowName = "WaivedNotes";
var strRetVal = null ;
var iLaunchWidth = 400 ;
var iLaunchHeight = 200 ;
var objForm = document.forms["frmActRoster"];
var strPath = _UTL_GetPagePath("management/LMS_ActRosterWaived.aspx?Status=" + strStatus);
I have added the strStatus param to the end of my URL which calls the .aspx page.
At this point this is where I'm confused.
What do I add to my .aspx page to store this value?
From the .aspx page it calls a method:
LMS_WaivedNotes_Show_UI();
This calls into the .aspx.js page which renders the HTML.
function LMS_WaivedNotes_Show_UI()
{
pc.Logger.DebugFunctionEntry("LMS_WaivedNotes_Show_UI");
var objHtml = null;
var objHtmlTable;
etc......
From this page I need to have the strStatus available to me in order to use it in an if statment.
Thank you!
You can use an ASPX HiddenField control. In your ASPX code-behind Page_Load method, get the querystring parameter and set the HiddenField value.
protected override void Page_Load(object sender, EventArgs e) {
var querystring = this.Request.QueryString["strStatus"];
this.MyHiddenField.Value = querystring;
}
You can then access this strStatus value in javascript:
var strStatus = document.getElementById('<%= MyHiddenField.ClientID %>');
However, if you only require this strStatus value for use in JavaScript, it would be more efficient to just get the query string value directly using JavaScript.
https://davidwalsh.name/query-string-javascript
Hope this helps.

Sharepoint 2013 - User profiles JSOM

I have this part of code which should get me for example the "title" of the current user in Sharepoint, but everytime it gives me error: Common Language Runtime detected an invalid program.
<script type="text/javascript">
var personProperties;
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
function getUserProperties() {
// Replace the placeholder value with the target user's credentials.
// var targetUser = "domainName\\userName";
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
personProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(personProperties);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
// Get a property directly from the PersonProperties object.
var messageText = personProperties.get_userProfileProperties()['Title'];
alert(messageText);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
alert(args.get_message());
}
</script>
Do you have any ideas why it is happening?
Thank you for any suggestions.
Tom
You can make use of SP.SOD.executeFunc to load the files in the correct manner.
Try the below code:
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {
// Make sure PeopleManager is available
SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager', function() {
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
personProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(personProperties);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
// Get a property directly from the PersonProperties object.
var messageText = personProperties.get_userProfileProperties()['Title'];
alert(messageText);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
alert(args.get_message());
}
});
});

ServiceNow UI Page GlideAjax

I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}

capturing a specific value from a cookie javascript

I have a cookie set up which has data stored in the following format:
{"g":"776","f":"88876","hit":"true","TESTVALUE":"this is the value i want to capture"}
I want to capture "TESTVALUE" in its own variable.
I am using this script to actually capture the cookie data (where the cookie is called "chocolateChip":
var getCookie = function (name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
} // code indentation
var cookie = getCookie(chocolateChip);
Im then using the following script to pass the "testvalue" string to its own variable:
var test = cookie.TESTVALUE;
However this does not seem to work.
The cookie value is a JSON string, which you need to parse to get an actual JS object.
Try this:
var cookie = getCookie(chocolateChip);
var test = JSON.parse(cookie).TESTVALUE;
Or, if you need to access more properties:
var cookie = getCookie(chocolateChip);
var cookieObject = JSON.parse(cookie);
var testValue = cookieObject.TESTVALUE;

Unable to call function within same GAS script

I have two function, one reads the Cell value upon change.
And the second one makes a Request to a URL and gets the response.
function onEdit(e) {
var range = e.range;
var data = range.getValue();
Logger.log(data)
Logger.log(test());
}
function test() {
var url = 'apps.compete.com/sites/wholesalerhinestones.org/trended/UV/?apikey=[YOUR API KEY HERE]';
var response = UrlFetchApp.fetch(url);
Logger.log(response);
}
Problem is that, test() runs successfully and Logs the output to Console but upon Cell change event, cell's value is logged but test() is not called.
One of the issues here is you're not actually calling the function, nor are you returning anything should it be called.
It should look something like this:
function onEdit(e){
var range = e.range;
var data = range.getValue();
Logger.log(data)
var testedFunction = test();
Logger.log(testedFunction);
}
function test(){
var url = 'YOUR-URL-HERE';
var response = UrlFetchApp.fetch(url);
Logger.log('Response code: ' + response.getResponseCode());
return response
}
The second issue that you're having here is that your using a Simple trigger which does not allow you to access services which require authorization.
Instead using an Installable trigger for 'onEdit' might do the trick. (This is what I was using, but I was testing against 'Google.com'). It should look like this:

Categories

Resources