I am trying out JSOM in Sharepoint 2016. I have made a WebPart containing the following code -
<div id="user-output"></div>
Movie Title: <input type="text" id="movie-title" /><br />
Description: <input type="text" id="movie-description" /><br />
<button type="button" id="submit-button">Add Movie</button>
<div id="movies-output"></div>
<script type="text/javascript" src="/SiteAssets/jquery-3.2.1.min.js"></script>
<script type="text/ecmascript" src="../_layouts/15/SP.UserProfiles.js"></script>
<script type="text/javascript">
$(function () {
$('#submit-button').on('click', function () {
var context = SP.ClientContext.get_current();
var movies = context.get_web().get_lists().getByTitle('Movies');
var movieCreationInfo = new SP.ListItemCreationInformation();
var movie = movies.addItem(movieCreationInfo);
movie.set_item("Title", $('#movie-title').val());
movie.set_item("MovieDescription", $('#movie-description').val());
movie.update();
context.load(movie);
context.executeQueryAsync(success, failure);
});
function success() {
$('#movies-output').text('Created movie!');
}
function failure() {
$('#movies-output').text('Something went wrong');
}
var upp;
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
//SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager', getUserProperties);
//SP.SOD.executeFunc('SP.UserProfiles.js', getUserProperties);
function getUserProperties() {
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
upp = peopleManager.getMyProperties();
clientContext.load(upp, 'UserProfileProperties');
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
$('#user-output').html('User Name: ' + upp.get_userProfileProperties()['PreferredName'] +
'<br/>Department: ' + upp.get_userProfileProperties()['Department'] +
'<br/>Designation: ' + upp.get_userProfileProperties()['Title'] +
'<br/>Employee ID: ' + upp.get_userProfileProperties()['EmployeeID'] +
'<br/>Branch Code: ' + upp.get_userProfileProperties()['branchCode']
);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
$('#user-output').text("Error: " + args.get_message());
}
});
What this code does is -
Show user information in user-output div at document load ready
Saves a movie record when Add Movie button is clicked
However, for some reason, when Add Movie button is clicked, the code adds two movies instead of one. I think it has something to do with the ClientContext. But I am not sure why, or how to solve it. Can anyone help?
I am not sure how it happened, or if it's a bug, but while fiddling with the page source to find out why double posting was occurring, I saw that my web part code was being rendered twice in the page. One part was visible, and another was under a hidden div. However, when I went to edit page to delete the hidden web part, I couldn't. So I restored my page to the template version and re-added the web part. After that the web part was working correctly. There were no problems with the code.
Related
Background:
I'm coming from the server-side world of Rails, and trying to figure out the Netlify static html + serverless functions approach to doing a few extremely basic landing page web apps which need a serverless function to insert data into an HTML page.
I'm trying to start with the simplest possible case of an HTML page with a form and a serverless function that returns a result back to the page. (e.g., no static site generators).
I have not found any Netlify tutorials that show how a HTML page can have a form that posts to a function which then returns the result of that function back into the same web page.
The simplest sample app I can think of is a page asks a question, the user POSTs their answer to a serverless function, and the same HTML page is updated with the result of the function... a trivial case being to display "your answer was X" above the form. (It is immaterial to me whether the actual page is rewritten again with the result string included, or the result string is dynamically inserted by somehow poking the string to the div, so long as the result string originates in a serverless function; integrating serverless functions results with HTML pages is what I'm trying to learn.)
In the code below a simple HTML page below displays a form, the form POSTs an answer to a javascript function check_answer.js, and the javascript function erases the current page and displays the string "Your answer was XXXX".
That was simple to do, and lots of tutorials show how to have a function accept a form post then return a result string to the browser (overwriting the prior page).
My question:
How can the serverless function insert the result string back into the original HTML page (at the div id="answer") instead of outputting the result to a blank page?
Current code:
# index.html
<html>
<head>
<title>A test form</title>
</head>
<body>
<div id="answer">
</div>
<p>How much is 1 + 3?</p>
<p>form using POST:</p>
<form method="post" name="calc 2" action="/.netlify/functions/check_answer" id="calcform2" data-netlify="true" >
<p>
<label for="my_answer">Answer:</label>
<input type="text" name="my_answer" id="my_answer">
<label for="my_comment">Comment:</label>
<input type="text" name="my_comment" id="my_comment">
</p>
<p>
<input type="submit">
</p>
</form>
</body>
</html>
# functions/check_answer.js
exports.handler = async event => {
console.log(event.queryStringParameters);
console.log(event);
console.log(event.body);
if (event.httpMethod == 'POST')
{
console.log('is POST');
var params = parseQuery(event.body);
console.log(params);
var answer_string = params['my_answer'];
}
else
{
console.log('is GET');
var answer_string = event.queryStringParameters.my_answer || 'empty'
};
return {
statusCode: 200,
body: `Your answer was ${answer_string}`,
}
}
// handle parsing form query aaaa=bbbbb&cccc=dddd into hash object
// from https://stackoverflow.com/a/13419367/597992
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
I have one list in sharepoint where user created one item on 25/11/2019,9:57PM but when today I tried to fetch data through REST get method it shows 26/11/2019,3:27AM.
When I look item in sharepoint list it shows correct date but when I try to fetch using REST it changes.
I want same date as in back end
SharePoint store datatime as UTC time so you need to convert to local datatime.
<script type="text/javascript">
function test() {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var regionalSettings = web.get_regionalSettings();
var localDueDate = regionalSettings.get_timeZone().utcToLocalTime('2019-02-26T17:15:00Z');
context.executeQueryAsync(
Function.createDelegate(this, function () {
console.log(localDueDate.m_value);
}),
Function.createDelegate(this, function (sender, args) {
alert('Query failed. Error: ' + args.get_message());
})
);
}
</script>
<input id="Button1" type="button" onclick="test()" value="button" />
I simply don't know JS well enough to determine the issue. I'm sure it's glaring at me, in plain sight. I just need the button to function like a button. When I move the cursor over the button and click, neither do anything.
I've tried adding the type, as you can see.
<!-- Load Stripe.js on your website. -->
<script src="https://js.stripe.com/v3"></script>
<!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. -->
<button
style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em"
id="checkout-button-plan_555xxx555"
role="link"
type="button"
>
Checkout
</button>
<div id="error-message"></div>
<script>
(function() {
var stripe = Stripe('pk_test_555xxx555');
var checkoutButton = document.getElementById('checkout-button-plan_G2Z8GjQU8ZihZw');
checkoutButton.addEventListener('click', function () {
// When the customer clicks on the button, redirect
// them to Checkout.
stripe.redirectToCheckout({
items: [{plan: '555xxx555', quantity: 1}],
// Do not rely on the redirect to the successUrl for fulfilling
// purchases, customers may not always reach the success_url after
// a successful payment.
// Instead use one of the strategies described in
// https://stripe.com/docs/payments/checkout/fulfillment
successUrl: window.location.protocol + '//cozelosdata.com/success',
cancelUrl: window.location.protocol + '//cozelosdata.com/canceled',
})
.then(function (result) {
if (result.error) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer.
var displayError = document.getElementById('error-message');
displayError.textContent = result.error.message;
}
});
});
})();
</script>
Your id for the button is wrong.
<button id="checkout-button-plan_G2Z8GjQU8ZihZw" role="link" type="button">Checkout</button>
**I have created a custom edit form for a SharePoint online custom list. Where I have created a custom button via which I will start a Workflow.
the issue is I am not able to call that function on button click. I have used a single comma also for the function call
I have created a custom edit form for a SharePoint online custom list. Where I have created a custom button via which I will start a Workflow.
The issue is I am not able to call that function on button click. I have used a single comma also for function call**
HTML Button Code:
<td class="ms-toolbar" nowrap="nowrap" align="right">
<input type="button" runat="server" value="Assign To Next Step" name="AssignToNextStep" onClick="startWorkflow()"/>
</td>
JavaScript Function Code is:
<script type="text/javascript">
function startWorkflow()
{
alert("Inside");
try
{
showInProgressDialog();
var ctx = SP.ClientContext.get_current();
var wfManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());
var subscription = wfManager.getWorkflowSubscriptionService().getSubscription("My Workflow ID");
ctx.load(subscription, 'PropertyDefinitions');
ctx.executeQueryAsync(
function(sender, args)
{
wfManager.getWorkflowInstanceService().startWorkflow(subscription, "");
ctx.executeQueryAsync(
function(sender, args)
{
closeInProgressDialog();
},
function (sender, args)
{
closeInProgressDialog();
alert(errorMessage);
});
});
}
catch(ex)
{
alert(ex);
dlg.close();
}
}
</script>
That Function was out of Scope. I mean I just changed the place of that function.
How do you insert the code? Have you checked the developer tools in your browser if it shows any errors?
Try to add
onClick="startWorkflow();return false;"
In your code.
I'm using the Articles and Users implementation into Meanjs built-in app.
List of articles (View) with the button for every item:
<a data-ng-controller="MyArticlesController" data-ng-repeat="article in articles" class="list-group-item">
<button data-ng-click="addArt2me()" class="glyphicon glyphicon-plus addArt2me" ></button>
<h4 class="list-group-item-heading" data-ng-bind="article.title"></h4>
<p> {{article.content | limitTo:140}} </p>
</a>
And here the controller with the trigger function $scope.addArt2me():
'use strict';
angular.module('users').controller('MyArticlesController', ['$scope', 'Articles', 'Users', '$location',
function($scope, Articles, Users, $location) {
var myUser = new Users($scope.user);
$scope.addArt2me = function() {
var myArticle = new Articles($scope.article);
myUser.userArticles.push(myArticle._id);
myUser.$update(function(response) {
console.log("Actualize!! con : " + user.userArticles.length + "__" + response);
}, function(errorResponse) {
console.log("updatError: " + errorResponse);
$scope.error = errorResponse;
});
}
}
]);
In the user's model I've an array of articles._id userArticles.
The View renders a list of articles with a button that triggers the function addArt2me() in the controller, which pushes and updates the myArticle._id inside ´userArticles´.
It works successfully and saves the element into DB :)
console: Actualize!! con : 60__[object Object]
...but only the first time, the next time it triggers an error :(
PUT http://localhost:3000/users 400 (Bad Request)
updatError: [object Object]´
Do I need to deal with some kind of service to update the USERS module being in ARTICLES module?
Can't I just update the model of the user with Mongoose?
Why does it works well for the first saved article ?
Any guide is very appreciated. Thanks!
I just founded, after 2 day of looking for it.
Needed to declare the User Model, outside the subcontroller because it iterates for every article.
so move ´$scope.myUser = new Users($scope.user);´ into ´ArticlesController´ Did the job!
Thanks for your time!