Send a wall post using Jquery's AJAX (Post) - facebook

I'm trying to post a wall message from a local desktop application (I can't use the FB JS SDK).
Here's a a snippet of my code
var url = "https://graph.facebook.com/me/feed";
var params = "access_token=" + token + "&message=" + encodeURI(text);
$.ajax({
crossDomain: true,
data: params,
dataType: "jsonp",
url: url,
type: 'POST',
success: function (data) {
if (callback) {
var isOK = (data && data.id && !data.error);
callback(isOK, data);
}
},
error: function (data, e1, e2) {
}
});
The request ignores the message parameter.
I receive a list of feeds as it were a GET request.
I've tried to set the parameters as map but it didn't help.
BTW - when using CURL (in C++) i manage to post the data correctly.
Any ideas why it ignores the parameters?

I would put the "params" into the data element like so:
var url = "https://graph.facebook.com/me/feed";
$.ajax({
crossDomain: true,
data: { access_token: token, message: text },
dataType: "jsonp",
url: url,
type: 'POST',
success: function (data) {
if (callback) {
var isOK = (data && data.id && !data.error);
callback(isOK, data);
}
},
error: function (data, e1, e2) {
}
});
Let jQuery encode the parameters from there.

Below worked fine in Jquery 1.6.4 + jquery.mobile-1.0rc2 by setting $.mobile.allowCrossDomainPages = true; in mobileinit bind
$.ajax( {
url : "https://graph.facebook.com/me/feed",
type : "POST",
data : "access_token=" + your_access_token + "&message=my first wall post",
cache : false,
success : function(res) {
if (!response || response.error) {
alert("Couldn't Publish Data");
} else {
alert("Message successfully posted to your wall");
}
},
error : function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
}
});

Related

Sharepoint list item using Api Rest

I need to get a list's items, so I created this function
export function retrieveSPItems(spToken, alias) {
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/ItemCount`;
var myHeaders = new Headers({
Accept: "application/json;odata=nometadata",
Authorization: spToken,
});
return fetch(url, {
method: "get",
headers: myHeaders,
}).then((response) => response.json());
}
As a output I get 3000.
when I change the url to
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/Items`;
I get an empty list!
PS :
It's work in Postman with no problem
The token is generated by adaljs :
Get Token
authContext.acquireToken(SP_BASE_URL, function (error, token){....})
Adal config
export const adalConfig = {
tenant: CURRENT_TENANT,
clientId: CURRENT_APP_ID,
endpoints: {
api: CURRENT_APP_ID,
graph: GRAPH_BASE_URL,
sharepoint: SP_BASE_URL,
},
cacheLocation: "localStorage",
validateAuthority: true,
};
So I need to know :
what the reason fot this issue?
How can I fix it?
It's too general information, you need debug and figure out the detailed error information.
My test demo:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="Scripts/adal.js"></script>
<script type="text/javascript">
var authContext = null;
var user = null;
(function () {
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: 'xxx.onmicrosoft.com',
clientId: '9afc37cb-x-x-x-xxx',
postLogoutRedirectUri: window.location.origin,
endpoints: {
graphApiUri: "https://graph.microsoft.com",
sharePointUri: "https://xxx.sharepoint.com/",
},
cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
};
authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
//$errorMessage.html(authContext.getLoginError());
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
user = authContext.getCachedUser();
if (!user) {
authContext.login();
}
//authContext.acquireToken(window.config.clientId, function (error, token) {
// console.log('---');
//})
authContext.acquireToken(window.config.endpoints.sharePointUri, function (error, token) {
alert(token);
if (error || !token) {
console.log("ADAL error occurred: " + error);
return;
}
else {
var listUri = window.config.endpoints.sharePointUri + "sites/lee/_api/web/lists/GetByTitle('mylist')/items?$select=Title";
$.ajax({
type: "GET",
url: listUri,
headers: {
"Authorization": "Bearer " + token,
"accept": "application/json;odata=verbose"
}
}).done(function (response) {
console.log("Successfully fetched list from SharePoint.");
var items = response.d.results;
for (var i = 0; i < items.length; i++) {
console.log(items[i].Title);
$("#SharePoint").append("<li>" + items[i].Title + "</li>");
}
}).fail(function () {
console.log("Fetching list from SharePoint failed.");
})
}
})
}());
</script>

Form Recognizer Anzalyze: Data loading error - 415

I am trying to call the form-recognizer API using SAPUI5 (Jquery / AJAX) post method. I am able to read the same pdf using RESTAPI client. The API when called from Javascript gives the below error.
The issue seems to be around data in the body of the ajax post method. Any suggestion/help is highly appreciated.
Error Message :
415 Unsupported Media Type
{"error":{"code":"2018","innerError":{"requestId":"a12dc9f8-b22f-4602-85d8-7330b16593f7"},"message":"Content
parsing error."}}
Javascript code :
onChange: function(oEvent) {
// var that = this;
var reader = new FileReader();
var file = oEvent.getParameter("files")[0];
var raw;
reader.onload = function (e) {
raw = e.target.result;
//alert(raw);
var sUrl2 = "https://formrecognizerforsap.cognitiveservices.azure.com/formrecognizer/v1.0-preview/custom/models/{mymodelid>/analyze";
jQuery.ajax({
type: "POST",
url: sUrl2,
context: this,
crossDomain: true,
data: raw,
beforeSend: function (xhr) {
xhr.setRequestHeader("content-type", "application/pdf");
xhr.setRequestHeader("ocp-apim-subscription-key", "my-subscription id");
},
error: function (jqXHR, textStatus, errorThrown) {
sap.m.MessageToast.show(errorThrown);
},
success: function (oData, status, jqXHR) {
sap.m.MessageToast.show(status);
}
});
};
reader.onerror = function (e) {
sap.m.MessageToast.show("error");
};
reader.readAsDataURL(file);
},
You could use atob javascript function to decode the Base64 string (link)
Example:
//plain text base64 WITHOUT datacontent and other stuff
let base64string = "JVBERi0xLjQKJ..."
let byteCharacters = atob(base64string);
jQuery.ajax({
type : "POST",
url : "<form recognizer url endpoint>",
context : this,
crossDomain: true,
data: byteCharacters,
beforeSend: function(xhr) {
xhr.setRequestHeader("ocp-apim-subscription-key", "<your_key>");
//To avoid specify pdf or image type use octet-stream
xhr.setRequestHeader("content-type", "application/octet-stream");
},
error : function(jqXHR, textStatus, errorThrown) {
console.error(errorThrown);
},
success : function(oData, status, jqXHR) {
console.info(status);
}
});
To get plain base64 string from pdf you could use this website to test: https://base64.guru/converter/encode/pdf

How to restrict user from submitting a form twice in sharepoint?

I'm working on a sharepoint forms
And I need to block edition for users after they submitted a date (data format), but I don't know if sharepoint allows it
Someone knows how can I do it?
For OOB list form, you could use presaveaction to do client validation.
In this function, you could call rest api to check whether the item submitted already, if submitted, return false then the form won't be saved.
Sample demo:
<script type="text/javascript" src="/_layouts/15/JS/jquery.min.js"></script>
<script type="text/javascript">
function PreSaveAction() {
var check = false;
var listid = _spPageContextInfo.pageListId.replace('{', '').replace('}', '');
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'" + listid + "')/items",
type: 'GET',
async: false,
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function (data, textStatus, jqXHR) {
var count = data.d.results.length;
if (count < 5) {
check = true;
} else {
alert('over max items');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
})
return check;
}
</script>

FB API email 'undefined' for some users

I have an MVC application and i retry Facebook value with this code:
FB.login(function (response) {
if (response.status == 'connected') {
var userId = response.authResponse.userID;
var userToken = response.authResponse.accessToken;
FB.api(
'/' + userId,
{ fields: 'name,email,first_name,last_name' },
function (userInfo) {
if (userInfo && !userInfo.error) {
var uf = new FormData();
uf.append("email", userInfo.email);
uf.append("userId", userInfo.id);
uf.append("name", userInfo.name);
uf.append("first_name", userInfo.first_name);
uf.append("last_name", userInfo.last_name);
var url = "/Account/ExternalRegisterFacebook";
$.ajax({
type: "POST",
url: url,
dataType: 'json',
contentType: false,
processData: false,
data: uf,
error: function () {
},
success: function (responseLogin) {
}
});
}
});
}
});
I can correctly log with my account but when i use another Facebook account i have all user value except email, that is 'undefined'.
I have read a lot of posts but i haven't understand how to solve this type of problem. I don't know if is an application error or a security information of each single Facebook profile.
Thanks to all

Get all replies in SharePoint Sitefeed using REST api

I'm trying to use RESTful services to return all replies in a SharePoint sitefeed. Currently, I am successfully using this code to retrieve the sitefeed's posts:
function getFeed(){
var feed;
var reply;
var rCounter;
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/actor(item=#v)/feed?#v=%27https://<mysite>.sharepoint.com/<sitename>/newsfeed.aspx%27",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
myFeed = $(data);
console.log(myFeed);
for (i = 0; i < myFeed[0].d.SocialFeed.Threads.results.length; i++) {
feed = (myFeed[0].d.SocialFeed.Threads.results[i].RootPost.Text);
console.log(myFeed[0].d.SocialFeed.Threads.results[0].Actors.results[1].Name + ": " + feed);
if (myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length >0){
rCounter = myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length;
for (j = 0; j < myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length; j++) {
rCounter--;
reply = myFeed[0].d.SocialFeed.Threads.results[i].Replies.results[rCounter].Text;
console.log(reply);
}
}
console.log("* * * * * * * * *");
}
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}
However, this gives me the posts but with only the two latest replies. According to this MSDN post, I need to use a POST method to get all replies and pass in the thread ID. So I made a new function:
function getPost(){
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/post(ID=ai)/?#ai='8.211b75cd6dc84fe4bc6c3e9f46971f51.97717348cd3048768103d55751dc0e2d.211b75cd6dc84fe4bc6c3e9f46971f51.819bde2276b948a8a120964289476489.17c08f26b90a4b659ff1fcfb0ede4025.5.5.1'",
method: "POST",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
console.log($(data));
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}
When I run this new function, I get a 403 (FORBIDDEN) error. Can someone tell me what I'm doing wrong?
try passing headers like below.
function getPost(){
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/post(ID=ai)/?#ai='8.211b75cd6dc84fe4bc6c3e9f46971f51.97717348cd3048768103d55751dc0e2d.211b75cd6dc84fe4bc6c3e9f46971f51.819bde2276b948a8a120964289476489.17c08f26b90a4b659ff1fcfb0ede4025.5.5.1'",
method: "POST",
headers: { "Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val() },
success: function (data) {
// Returning the results
console.log($(data));
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}