Post a message as a page using JAVASCRIPT - javascript

I had successfully post a message to my own Facebook page but it was posted as a visitor(I want post as a page). I'm not sure where i missed and also i confused to the page access token.
$('#btn-fb').click(function () {
getPageAccess(function (page_id){
postToFB(page_id,'sien');
});
//postStatus();
});
function getPageAccess(callback) {
FB.login(function (response) {
// handle the response
if (response.authResponse) {
FB.api('/' + page_id + '', {fields: 'access_token'}, function (response) {
if (response && !response.error) {
callback(page_id);
}
});
}
}, {scope: 'manage_pages,publish_pages'});
}
function postToFB(page_id, message) {
FB.api(
"/" + page_id + "/feed",
"post",
{
"message": message
},
function (response) {
if (response && !response.error) {
/* handle the result */
}
else {
}
}
);
}

You need to use a Page Token to post as Page, right now you are using a User Token. You are asking for the Page Token (fields parameter), but you never use it and you donĀ“t add it as callback parameter:
{
'message': message,
'access_token': pageToken
}

Related

To post on facebook page using javascript SDK with page access token

I am trying to post to my facebook's wall using javascript SDK. I am first getting user access token. Then using user access token i am getting page access token and including it while posting to a wall. I'm getting following error
here's my code : First am trying to login using FB.login
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.'+JSON.stringify(response));
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'manage_pages,publish_pages'});
Then trying to post to a page.
var body = 'Reading JS SDK documentation';
FB.getLoginStatus(function(response) {
console.log('login status',response);
if(!(response.status === 'connected')){
location.href = './fb-login.html';
} else {
uID = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log('accesstoken::',response.authResponse.accessToken);
FB.api('/me', {fields: 'last_name'}, { access_token : accessToken } ,function(response) {
console.log(response);
});
//get list of pages
if(accessToken!=null){
FB.api('/me/accounts','get',{ access_token : accessToken },function(response){
console.log('resp of pages',response);
if(response!=null){
var data = response.data;
pageAccessToken= data[0].access_token;
console.log('pageAccessToken::',pageAccessToken);
FB.api('/6599048*******/feed', 'post', {message :body, access_token : pageAccessToken }, function(response) {
console.log('response',response)
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
});
}

Calling sync ready made async ajax javascript function

I want to call this function on button click after login and wait for result, to get token value. This function cannot be changed, it is async and supplied from other currently unavailable team.
I already tried something like this, but with no success. I get web service results, but I can't write appropriate sync call to wait to return token.
function getToken() {
param1 = "123456";
ajax_oauth(param1, function (success, response) {
success: return response.token;
});
}
function ajax_oauth(param1, callback) {
APP.debug("oauth login with param1 " + param1);
try {
APP.blockUI();
var DeviceID = APP.readRegistry(APP_CONFIG.REGISTRY.DeviceID);
//---------------------------------------------------------------
$.ajax(
auth_token_url,
{
method: "GET",
accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
'param1': param1,
'deviceId': DeviceID
}),
xhrFields: {
withCredentials: false
},
statusCode: {
201: function (response) {
APP_STATE.hasOauth = true;
APP.debug('got response 200 from oauth');
auth.login(response.token); //TODO read expiration from token
try {
var decoded = jwt_decode(response.token);
APP_STATE.uid = decoded.uid;
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
},
401: function () {
},
500: function () {
},
503: function () {
}
},
success: function (response) {
APP.unblockUI();
APP_STATE.restAvailable = true;
},
error: function (jqXHR, textStatus, errorThrown) {
APP.unblockUI();
APP_STATE.restAvailable = false;
APP.restError(auth_token_url, jqXHR, errorThrown, textStatus);
APP.callback(callback, false);
}
}
);
} catch (err) {
APP.error("unable to do oauth login, " + err);
}
};
After user clicks on login button, I want to call function ajax_oauth and to return token if params ok. If not, to return login error. Login can't be async, as far as I can see.
For whatever reason you can't tap into the original ajax response, you could intercept the request using $.ajaxPrefilter.
From your code it looks like auth_token_url has a global reference. You could use this to intercept the call by matching the outgoing request on the resource URL.
$.ajaxPrefilter('json', function(options, originalOptions, jqXHR) {
if (options.url === auth_token_url) {
jqXHR.done(function(response) {
try {
var decoded = jwt_decode(response.token);
console.log(decoded);
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
});
}
});
Note that this needs to be declared well before the request is made preferably after jQuery is loaded.

Jquery Terminal register & login

I have question, i want user register then login but here it's error anyone can help me ? i saw the documentation . here is link of the documentation jquery termi[jquery terminal]1nal
here is my script:
if (command == 'register') {
term.push(function(command, term) {
term.pause();
$.ajax({
url: "register.php",
type: "post",
data: {data_register : command },
success: function (msg) {
term.echo(yellow('Data Saved Successfully !'));
term.resume();
},
error: function(jqXHR, textStatus, errorThrown) {
term.resume();
}
});
},
{
prompt: " > "
});
} else if (command == 'login'){
login: function(user, password, callback) {
if (user == 'demo' && password == 'secret') {
callback('SECRET TOKEN');
} else {
callback(null);
}
}
}
this line's error :
else if (command == 'login'){
login: function(user, password, callback) {
if (user == 'demo' && password == 'secret') {
callback('SECRET TOKEN');
} else {
callback(null);
}
}
}
Thank you
You have invalid JavaScript you have label and function declaration, which should be put in an object like this:
var x = {
login: function() {
}
};
which should be part of object in second argument which is options object.
.terminal(function(command) {
if (command === 'register') {
}
}, {
login: function(...) {
...
}
});
and for your exact problem on having login command, that login you in, you need to invoke login method like this:
} else if (command == 'login'){
term.login(function(user, password, callback) {
// to get the token you should send user and password to the server
if (user == 'demo' && password == 'secret') {
callback('SECRET TOKEN');
} else {
callback(null);
}
});
} else if (term.token()) {
// here are commands that will only work after user login
// but you need to know that user may add token in developer tools
// so you should use additional check if token is valid by sending token
// to the server, or if you're invoking command on the server then just
// send the token and validate it there
} else {
term.error('invalid command');
}

How use the success call back in a delete ajax [NODE.JS]

I'm using the following code to delete a collection in my db:
Client:
$('.destroy').click(function() {
if(confirm("Are u sure?")) {
$.ajax({
type: 'DELETE',
url: '/destroy/' + dataId,
success: function(response) {
console.log('Success');
}
});
} else {
alert('Cancelled');
}
});
Server:
app.get('/destroy/:id', function(req, res) {
var id = req.param("id");
MyModel.remove({
_id: id
}, function(err){
if (err) {
console.log(err)
}
else {
console.log('Collection removed!');
}
});
});
Is working, if i click in the destroy button and reload the page, the collection will not be there, but the success callback function with the: [console.log('Success');] is not running..
I need send a callback from the server to the client ir order to make the success function run???
How make the console.log('Success'); run??
Thanks.
The ajax call probably just times out, as it's never getting a response back from the server.
Send a response from the server
app.get('/destroy/:id', function(req, res) {
var id = req.param("id");
MyModel.remove({
_id: id
}, function(err){
if (err) {
res.end('error');
}
else {
res.end('success');
}
});
});
Then catch it
$.ajax({
type : 'DELETE',
url : '/destroy/' + dataId,
success : function(response) {
if ( response === 'error' ) {
alert('crap!');
} else if (response === 'success' ) {
alert('worked fine!');
}
}
});
This is a simplified example, you can return whatever you like, send statusCodes or whatever.

Facebook JS API - How to redirect user after login

I have the following code:
FB.getLoginStatus(function (response) {
if (response.session) {
} else {
FB.ui({
method: 'oauth',
perms: 'email,publish_stream',
},
function (response) {
if (response && response.installed) {
window.location.reload();
}
});
}
});
What I want is to basically redirect the user to the same page so that the serverside can use the REST API. Is there anyway to make this work?
Subscribe to the login event:
FB.Event.subscribe('auth.login', function (response) {
window.location.reload();
});
Use this.
FB.Event.subscribe('auth.sessionChange', function (response) {
if (response.session) {
//user is logged in!
window.location = document.URL;
}
});

Categories

Resources