How to get all survey answer by current user with REST Api Sharepoint? - rest

In sharepoint survey API:
Get all question: https://site/_api/Web/Lists/getByTitle('Survey')/fields?$filter=(CanBeDeleted eq true)
Get all answer: https://site/_api/Web/Lists/getByTitle('Recognition%20Awards%202019')/items
Get all answer by current user login: ???
Please help me.

We can use _spPageContextInfo.userId to get the current login user Id, then using $filter=AuthorId eq UserId to get all the answer by current user login.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getItems() {
var listTitle="Recognition Awards 2019";
var currentUserId=_spPageContextInfo.userId;
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listTitle+"')/items?$filter=AuthorId eq "+currentUserId,
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
//
},
error: function (err) {
//alert(err);
}
});
}
</script>
<input id="Button1" type="button" value="Get Items" onclick="getItems()" />

Related

How to create folders on SharePoint 2019 using REST calls via postman? Getting 403: Forbidden error

I am using the below call to create a folder on SharePoint2019:
POST http://<site>/_api/web/folders
{
"__metadata": {
"type": "SP.Folder"
},
"ServerRelativeUrl": "/Shared Documents/Folder"
}
But I am getting the following error:
403 Forbidden: The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again.
Please check if you have got the valid form digest value in your side.
For example, if the site url is http://sp/sites/dev/
Then do a Post Request to this url http://sp/sites/dev/_api/contextinfo
Then use this form digest value in Request Header:
Here is a sample request to create folder using Rest:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnSubmit").on("click", function () {
createFolder();
});
}
function createFolder() {
var folderName = $("#txtFolderName").val();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/folders";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.Folder' },
'ServerRelativeUrl': 'Shared Documents/' + folderName
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
}
function onQuerySucceeded() {
$("#divResults").html("Folder created successfully !!!");
}
function onQueryFailed() {
alert('Error!');
}
</script>
<div>
<strong>Enter FolderName:</strong><br />
<input type="text" id="txtFolderName" /><br />
<input type="button" id="btnSubmit" value="Create Folder" />
</div>
<div id="divResults"></div>
Reference:
Some Help for Authorization Problems in SharePoint 2013 REST API

Post on Facebook wall with Javascript sdk

So, I'm trying to post on users wall using fb.api and I'm stuck.
Here is my code:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"><head><meta http- equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Example Of Posting To Wall Using Javascript Graph API</title>
<script type="text/javascript" src=""></script>
</head>
<body class="">
//the facebook sdk include
<div id="fb-root" class=" fb_reset">
<script>
var APP_ID="myAppID";
window.fbAsyncInit = initFacebook;
function initFacebook()
{
FB.init({
appId : APP_ID,
status : true, // check login status
cookie : false, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(onFacebookLoginStatus);
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
//the login function
function facebookLogin()
{
var loginUrl="http://www.facebook.com/dialog/oauth/?"+
"scope=publish_stream&"+
"client_id="+APP_ID+"&"+
"redirect_uri="+document.location.href+"&"+
"response_type=token";
window.location=loginUrl;
}
//Callback function for FB.login
function onFacebookLoginStatus(response)
{
if (response.status=="connected" && response.authResponse)
{
document.getElementById("txtEcho").innerHTML="Logged in.";
}
else
{
document.getElementById("txtEcho").innerHTML="Not logged in.";
}
}
//post to wall function
function postToWallUsingFBApi()
{
var data=
{
caption: 'This is my wall post example',
message: 'Posted using FB.api',
link: 'http://wwww.permadi.com/blog/',
}
FB.api('/me/feed', 'post', data, onPostToWallCompleted);
}
//the return function after posting to wall
function onPostToWallCompleted(response)
{
if (response)
{
if (response.error)
{
document.getElementById("txtEcho").innerHTML=response.error.message;
}
else
{
if (response.id)
document.getElementById("txtEcho").innerHTML="Posted as post_id "+response.id;
else if (response.post_id)
document.getElementById("txtEcho").innerHTML="Posted as post_id "+response.post_id;
else
document.getElementById("txtEcho").innerHTML="Unknown Error";
}
}
}
</script>
<input id="loginButton" type="button" value="Login To Facebook" onclick="javascript:facebookLogin();">
<input id="postToWallWithFBApiPrompt" type="button" value="Post To Wall Using FB.api" onclick="javascript:postToWallUsingFBApi();">
<div id="txtEcho"><b></b></div>
</body>
</html>
The problem here is that I receive this error code: An active access token must be used to query information about the current user.
I get that even if I use the log in button to get the code. Is there a possibility to add previously obtained access token in function postToWallUsingFBApi(). And can I change the /me/ with user id, so that way the user can be logged out and still post?
If you are doing client-side login that way, you have to extract the access token from the URL yourself afterwards – see https://developers.facebook.com/docs/howtos/login/client-side-without-js-sdk/#step3
Or you just use the FB.login method out of the JS SDK – a little easier, handles all the ecessary stuff “out of the box” – https://developers.facebook.com/docs/howtos/login/getting-started/#step4

How to find out who has published a post using my OG action

Hoping someone can point me in the right direction.
I have an open graph action that has finally been approved and is active on my app now. Is there any way to track who publishes a post using my OG action from within my app?
Here is the code I'm using for my action:
<script type="text/javascript">
function postEndorse()
{
FB.api(
'/me/namespace:endorse',
'post',
{ photo: '<?php the_permalink(); ?>' },
function(response) {
if (!response || response.error) {
alert('Error Occurred' + response + " " + response.error);
} else {
alert('Thank you!');
}
});
}
</script>
I am requesting the publish_actions permissions when people log in.
Thanks
The response in your JavaScript code above has the id of the action.
{
id: “{action-instance-id}”
}
You need to store your actions via database or otherwise. Once you have that you can make a call against it
/action-instance-id?fields=from.fields(id)
Which will give a response such as
{
"from": {
"id": "{user-id}"
},
"id": "{action-instance-id}"
}
There are many ways to store this data, one way would be AJAX to PHP/MySQL.
I suggest reading up on it. The following hasn't been tested, just gives an idea of how to send the data across. Think of it as pseudocode
Add jQuery to the <head>
<script src="jquery.js"></script>
Send the id of the user, like
<script type="text/javascript">
function postEndorse()
{
FB.api(
'/me/namespace:endorse',
'post',
{ photo: '<?php the_permalink(); ?>' },
function(response) {
if (!response || response.error) {
alert('Error Occurred' + response + " " + response.error);
} else {
FB.api(
response.id + "?fields=from.fields(id)",
function(resp) {
if (!resp || resp.error) {
alert('Error Occurred' + resp + " " + resp.error);
} else {
$.ajax({
type: "POST",
url: "fbdata.php",
data: { id: resp.from.id, actionid: resp.id }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
}
});
}
</script>
Then in fbdata.php something like
<?php
include("database.inc.php");
mysql_connect($server,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$id = mysql_real_escape_string($_POST['id']);
$actionid = mysql_real_escape_string($_POST['actionid']);
$database_entry = "INSERT INTO Actions (Id, Action) VALUES ('$id', '$actionid') ;
mysql_query($database_ntry) or die(mysql_error());
mysql_close();
?>
References that you should read
http://api.jquery.com/jQuery.ajax/
http://www.php.net/manual/en/mysql.examples-basic.php
What about if you change
/me/namespace:endorse to /users facebook id/namespace:endorse Then you can store the facebook id of the person and then track them back using that.

Publsih action in Open Graph giving error

I am using Post action in Open graph using the below code, but getting the error message "[Object Object]"
What might be the problem???, i followed all the step by step guidance to publish an action from this URL
https://developers.facebook.com/docs/opengraph/tutorial/#publish
<script type="text/javascript">
function postArticle() {
FB.api(
'/me/ICONSolutions-test:Read',
'post',
{ Article: 'http://fbwerks.com:8000/zhen/cookie.html' },
function (response) {
if (!response || response.error) {
alert(response.error);
} else {
alert('Successful! Action ID: ' + response.id);
}
});
}
</script>
<input type="button" value="POST" onclick="postArticle()" />
You're alert()-ing an object which has no toString method that gives a readable representation of the object.
Dump the value to the console instead, console.log(response) – and have a look at it in Firebug or a similar debugging tool that implements console.

Extracting user id from Facebook Javascript SDK session object

I am using Facebook's Javascript SDK "FB.ui" to pull up an OAuth dialog. Once you click allow, I need to capture the session object, extract the user id and use it further in my script. For some reason I cannot get this working properly, I keep getting undefined, even though the session does exist.
<script src="http://connect.facebook.net/en_US/all.js"></script>
<div id="fb-root"></div>
<script type="text/javascript">
FB.init({
appId : '***************',
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
if (response.session) {
//do something
} else {
FB.ui({
method: 'oauth',
display: 'page',
scope: 'email',
perms: 'email'
},
function(response) {
alert(response.session.uid); //returns underfined
});
}
});
</script>
To get the userID:
FB.getLoginStatus(function(response) {
alert(response.authResponse.userID);
});
When you login from login button of facebook then it stores cookies in your system that contains your access token that is also unique. That cookies contains your facebook id also.
Check your response. I bet it says something like "display" must be one of "popup", "iframe" or "hidden". Apparently the oauth dialog cannot be called with the default "page" display. And display: 'iframe' requires that you include an access_token, which is why you're calling the oauth dialog in the first place >:l .
I don't think FB.ui can currently be used to get the oauth dialog, unless you want to use a popup, which most everyone has blocked nowadays.
So I got this to work as I would like. This may not be the best way, but after much digging around and frustration I hope this could help somebody with the same question get on the right track.
JS source:
FB.getLoginStatus(function(response) {
if (!response.session) {
//initiate FB OAuth js popup dialog
FB.ui({
method: 'oauth',
display: 'page',
scope: 'email',
perms: 'email'
},
function(response) {
if (response.session) { //if permission Allowed
var thesession = response.session;
var thesession = eval('(' + thesession + ')'); //decode json
//POSTing to local file get.user_graph.php, to fetch user info
$.ajax({
type: "POST",
url: "get.user_graph.php",
data: "client_id=<?php echo $appId; ?>&client_secret=<?php echo $secret; ?>&sessions="+thesession.session_key+"&type=client_cred&uid="+thesession.uid,
dataType: "text",
success: function(user_graph){
var user_graph1 = eval('('+user_graph+')');
alert(user_graph1.name); //users name
alert(user_graph1.id); //users id
alert(user_graph1.email); //users email
alert(user_graph1.link); //users profile link
}
});
} else {
//if permission Not Allowed
}
});
}
});
get.user_graph.php source:
//exchange our session for an access_token
define('POSTURL', 'https://graph.facebook.com/oauth/exchange_sessions');
define('POSTVARS', 'client_id='.$_POST['client_id'].'&client_secret='.$_POST['client_secret'].'&sessions='.$_POST['sessions'].'&type=client_cred');
$curl_token = curl_init(POSTURL);
curl_setopt($curl_token, CURLOPT_POST,1);
curl_setopt($curl_token, CURLOPT_POSTFIELDS,POSTVARS);
curl_setopt($curl_token, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($curl_token, CURLOPT_HEADER,0);
curl_setopt($curl_token, CURLOPT_RETURNTRANSFER,1);
$token = curl_exec($curl_token);
$token_decoded = json_decode($token,true);
//get the user graph (personal info)
$user_graph = file_get_contents("https://graph.facebook.com/".$_POST['uid']."?access_token=".$token_decoded[0]['access_token']);
echo $user_graph;