Posting comment to Facebook from JavaScript - javascript

I have a Facebook application, a Facebook page and a website. When someone adds a comment to my website, I retrieve the comment text from the code below. What I want to do after that is to let my Facebook application post the same comment text to my Facebook page.
This is the JavaScript code I have so far on my website:
window.fbAsyncInit = function() {
FB.init({
appId: " . drupal_to_js($appid) . ",
status: true,
cookie: true,
xfbml: true,
channelUrl: " . drupal_to_js($channel_url) . "
});
FB.Event.subscribe('comment.create', function(response) {
var commentQuery = FB.Data.query('SELECT text FROM comment WHERE post_fbid=\'' + response.commentID + '\' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url=\'' + response.href + '\')');
FB.Data.waitOn([commentQuery], function () {
var commentRow = commentQuery.value[0];
var commentText = commentRow.text;
//TODO Post commentText to the Facebook page.
});
}); };

After an extensive search, here is the answer for those who are looking for it. Please read the comments inside the code, they will give you more information.
window.fbAsyncInit = function() {
FB.init({
appId: " . drupal_to_js($appid) . ",
status: true,
cookie: true,
xfbml: true,
channelUrl: " . drupal_to_js($channel_url) . "
});
FB.Event.subscribe('comment.create', function(response) { //trigger when comment is created
var commentQuery = FB.Data.query('SELECT fromid, text FROM comment WHERE post_fbid=\'' + response.commentID + '\' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url=\'' + response.href + '\')');
var userQuery = FB.Data.query('SELECT name FROM user WHERE uid in (select fromid from {0})', commentQuery);
FB.Data.waitOn([commentQuery, userQuery], function () {
var commentRow = commentQuery.value[0];
var userRow = userQuery.value[0];
var commentText = commentRow.text;
var commentUsername = userRow.name;
//Call this function to send an Ajax request to Facebook.
post_to_fb(commentText, commentUsername, response.href);
});
}); };
//This function will post to a Facebook page that has the ID $fb_page_id.
//The post format is like this, [NAME said:] POST e.g: [ObyYou said:] this is a test.
//Of course, you can change the format the way you want.
//You have to have an access key to have the permission to post on that page.
//Use the two sites at the bottom of this answer for help, (remember if you
//want to hard-code the access token, you have to create a permenant access token).
//Note that some variables and functions are PHP, since my JavaScript code is
//actually inside a PHP file.
function post_to_fb(commentText, commentUsername, commentLink) {
var strURL = 'https://graph.facebook.com/" . $fb_page_id . "/feed';
var params = 'link=' + commentLink + '&message=[' + commentUsername +'+said:]+' + commentText + '&access_token=" . $fb_page_access_token . "';
var xmlHttpReq;
xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open('POST', strURL, true);
xmlHttpReq.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlHttpReq.send(params);
}
Create A (permanent) access_token:
http://www.testically.org/2011/09/27/5-steps-to-automatically-write-on-your-facebook-page-wall-using-the-graph-api-without-a-logged-in-user/
http://php-academy.blogspot.com/2011/04/how-to-post-from-facebook-app-to.html

Related

Pubnub One to One Chat Sending Message to all users

This is My Pubnub Chat Code
var pubnub = PUBNUB.init({
publish_key : 'my_key',
subscribe_key : 'sub-key'
});
pubnub.subscribe({
channel : "{{$channel}}",
message : function(m){
$(".conversation-list").append(
'<li class="clearfix '+ m.clearifix +' ">' +
'<div class="chat-avatar">' +
'<img src="' + m.image + '">'+
'<i> {{date('h:i')}} </i>' +
'</div>' +
'<div class="conversation-text">' +
'<div class="ctext-wrap">' +
'<i> '+ m.name + '</i>' +
'<p>' + m.message + '</p>' +
'</div>' +
'</div>' +
'</li>'
).animate({scrollTop: $(".conversation-list")[0].scrollHeight}, 0);
$('.reply-text').val('');
},
//connect : publish
});
$('.send-reply-to-user').on('click', function (e) {
e.preventDefault();
if ($('.reply-text').val()== '')
return false;
else
console.log(pubnub.publish);
// console.log(this);
var user_to_id = $(".send-reply-to-user").attr('user_to_id');
var message = $('.reply-text').val();
var name = $('#user_name').val();
var image = document.getElementById("user_image").getAttribute("src");
var clearifix = $('#user_clearifx').val();
pubnub.publish({
channel : "{{$channel}}",
message: { name : name, message : message, image : image, clearifix : clearifix }
});
if ($.trim(message).length != 0) {
$.ajax({
url: '{{route('send:user:chat:message')}}',
cache: false,
method: 'POST',
data: {user_to_id: user_to_id, message: message, _token: '{{csrf_token()}}'},
beforeSend: function () {
},
success: function (result) {
}
})
}
});
This code is Working perfectly only problem is that messages are going to all users, I want to send msg to one to one user.
Example: User one: John send a message to User two Deo,
Example 2: John sends a message to Marry
and so on. Using Pubnub JS API, Backend as Laravel 5.6
I recommend using PubNub's opinionated JavaScript framework called ChatEngine. It takes away a lot of the heavy lifting involved with making chat with PubNub. Here is some example code to get you started making 1:1 private chats. Make sure you use the setup button to prepare the backend on your account.
<script src="https://cdn.jsdelivr.net/npm/chat-engine#0.9.5/dist/chat-engine.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Init ChatEngine with PubNub
const publishKey = '__Your_PubNub_Publish_Key__';
const subscribeKey = '__Your_PubNub_Subscribe_Key__';
const ChatEngine = ChatEngineCore.create({
publishKey,
subscribeKey,
}, {
globalChannel: 'global',
});
const user = {
uuid: 'randomstringofchars',
name: 'John Smith'
}
const chats = {};
ChatEngine.connect(user.uuid, user);
ChatEngine.on('$.ready', function(data) {
// store my new user as `me`
let me = data.me;
// returns a ChatEngine chat object
function makePrivateChat(theirUserId) {
const chatKey = [theirUserId, me.uuid].sort().join('-');
// Don't make the same 1:1 chat if it already exists
if (chats[chatKey]) {
return;
}
// true for private chat
const chat = new ChatEngine.Chat(chatKey, true);
chats[chatKey] = chat;
}
// Auto add a 1:1 chat to UI when invited by someone
me.direct.on('$.invite', makePrivateChat);
// Define a button for making new 1:1 chats in your UI
newOneToOneChatButton.on('click', function (event, theirUserId) {
someChatObject.invite(theirUserId);
});
});
</script>
Finally Fixed My issue, the private Channels working good , Actually problem was with my back-end. It was returning data from all the users i have fixed now its working fine.

Twitch Button (HTML/JScript w bootstrap)

Hello everyone I've tried everything I can think of to make this work. I know it does return stream = null or active through use in the browser, but It will not apply my buttons to my page. Not so good with javascript can anyone point me in the right direction.
<script type="text/javascript">
(function() {
var user_name, api_key;
user_name = "Undead_Atomsk";
api_key = "************************";
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name + '?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.write(Live!);
} else {
document.write(Offline!);
}
});
})();
</script
Took your advice and used browser tools "Completely forgot about those".
I added this line to my html.
I then made a .js file and used the following code everything works now the twitch API is just slow!
(function() {
var user_name, api_key, twitch_widget;
user_name = "Undead_Atomsk";
api_key = "********************";
twitch_widget = $("#twitch-widget");
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name +'?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.getElementById("twitch-btn").innerHTML = 'Live!';
} else {
document.getElementById("twitch-btn").innerHTML = 'Offline!';
}
});
})();

AngularJS - Facebook Sharer

I am trying to use the Facebook Share in AngularJS. Below is my function that is called when the user clicks on the FB icon.
$scope.shareFB = function(){
// Get configuration ID from service
configuratorService.storeConfiguration($scope.modelCode, function(configID){
// Use saved configuration id to create share link
var base = $location.absUrl().replace($location.url(), '');
var byoUrl = base + "/" + $scope.modelCode + "/resume/" + configID;
console.log(byoUrl);
var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=" + byoUrl, "pop", "width=600, height=400, scrollbars=no");
});
}
This function works fine when I try to share a url like "https://www.google.com/"
the Facebook Popup then has the URL = "https://www.facebook.com/sharer/sharer.php?u=https://www.google.com/"
When I use the function above:
byoUrl = "http://localhost:8000/#/15K6/resume/9295316837"
and the resulting FB popup has URL = "https://www.facebook.com/15K6/resume/9295316837"
Why does the "/sharer/sharer.php?=http://localhost:8000/#/" get cut off?
You shouldn't even try to share a localhost URL, as Facebook will never be able to scrape it. That's very likely why your URL gets cut off. Facebook tries to resolve it and scrape it, but it will never find it, so it makes a best effort to redirect within itself. Example:
https://www.facebook.com/sharer/sharer.php?u=http://localhost:8000/#/coke
Try to put your share logic in the controller. Something along these lines.
// Share posts
$scope.fbShare = function(post){
FB.ui(
{
method: 'feed',
name: post.title,
link: 'http://www.cengkuru.com/'+post.slug,
picture: '',
caption: '',
description: $filter('limitTo')($scope.post.body, 150),
message: ''
});
}
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR_APP_ID', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>

How do I pull phoneNumber from Linkedin Javascript API array

I appreciate any help with those familiar with the LinkedIn JavaScript API. Question: How do I pull in the phone number and email from the field array. In my example, posted to a php script, both phoneNumber and emailAddress are undefined when set to $_POST[''];:
<script type="text/javascript">
//Runs when the JavaScript framework is loaded
function onLinkedInLoad() {
IN.UI.Authorize().params({"scope":["r_fullprofile", "r_emailaddress", "r_contactinfo"]}).place();
IN.Event.on(IN, "auth", onLinkedInAuth);
}
//Runs when the viewer has authenticated
function onLinkedInAuth() {
IN.API.Profile("me").fields("id,firstName,lastName,phoneNumbers,emailAddress,positions").result(displayProfiles);
}
// 2. Runs when the Profile() API call returns successfully
function displayProfiles(profiles) {
var p = profiles.values[0];
var phone = profiles.values[0].phoneNumbers;
for (var i in p.positions.values) {
var pos = p.positions.values[i];
if (pos.isCurrent)
var company = pos.company.name;
}
//AJAX call to pass back vars to server
var http = new XMLHttpRequest();
var postdata= "id=" + p.id + "&fName=" + p.firstName + "&lName=" + p.lastName + "&phone=" + phone + "&email1=" + p.emailAddress + "&company=" + company;
http.open("POST", "../inc/linkedin.php", true);
use fields like this http://developer.linkedin.com/documents/profile-fields
Try this...
IN.API.Profile("me")
.fields('id,email-address,first-name,last-name,date-of-birth,phone-numbers,positions,num-connections')
.result(displayProfiles)
.error(displayErrors);

Issue in the faceebook auth dialog box

I have integrated Facebook login in my website using javascript SDK.. Everything is working fine except for the auth dialog box, which is showing only once for a user.Next time when the user logs it redirects without showing the auth dialog box.I want to show the auth dialog box each time the user logs.
This is the code I am using
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxx',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
if (window!=window.top) {
FB.Canvas.setAutoResize();
};
FB.getLoginStatus(function(response) {
if (response.authResponse) {
window.FBlogin = function(){
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
var query = FB.Data.query('select name,username, email, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
//document.getElementById('name').innerHTML = '<img src="' + rows[0].pic_square + '" alt="" />';
var name=rows[0].name;
var email=rows[0].email;
var uid=response.id;
var username=rows[0].username;
var pic=rows[0].pic_square;
});
});
}
else {
alert("error");
}
}, {scope: 'email'});
};
}
else {
var authbox = document.getElementById('FBauth');
authbox.innerHTML="";
var a = document.createElement('a');
a.setAttribute("href","javascript:void();");
a.setAttribute("onclick","FBlogin();");
authbox.appendChild(a);
window.FBlogin = function(){
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
var query = FB.Data.query('select name,username, email, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
var name=rows[0].name;
var email=rows[0].email;
var uid=response.id;
var username=rows[0].username;
var pic=rows[0].pic_square;
});
});
}
}, {scope: 'email'});
};
}
});
FB.Event.subscribe('auth.login', function () {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
var query = FB.Data.query('select name,username,email, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
var name=rows[0].name;
var uid=response.id;
var email=rows[0].email;
var username=rows[0].username;
var pic=rows[0].pic_square;
var page='';
$('<input />').attr({'type':'hidden', 'id':'fbname','value':email}).appendTo('#fbaccess');
});
})
});
FB.Event.subscribe('auth.logout', function(response) {
});
};
Everything is working fine except for the auth dialog box, which is showing only once for a user.Next time when the user logs it redirects without showing the auth dialog box.
If the user is already connected to your app and has given all of the requested permissions – then this is the intended behavior.
Calling FB.login again in this situation will open the popup, and close it again immediately.
I want to show the auth dialog box each time the user logs.
I can’t see the benefit of an app behaving in such a way.
Anyways, there is a parameter to explicitly request that the user re-authenticate: auth_type=reauthenticate. This will force the user to re-enter their password. See https://developers.facebook.com/docs/authentication/reauthentication/#client-side for details.
But I’m not sure that this is what you actually want.
Another way could be to delete permissions via your app, and then have them requested again via the scope parameter. That should bring up the Auth dialog again. For details on that, see https://developers.facebook.com/docs/reference/api/user/#permissions

Categories

Resources