Utilize Fb.api to automatically post on user's wall upon logging in

I want to utilize fb.api to make a single post on the logged-in user's wall. Here is the code snippet:

var params = {};
params['message'] = 'gegeegeggegall! Check out www.facebook.com/trashcandyrock for more info.';
params['name'] = 'gegeggeeg - gegegege';
params['description'] = 'Check out Tegegegeg! Win merch by playing and recommending to your friends.';
params['link'] = 'http://www.bblblba.com';
params['picture'] = 'http://summer-mourning.zoocha.com/uploads/thumb.png';
params['caption'] = 'Tgegegegeeg';

FB.api('/me/feed', 'post', params, function(response) {
  if (!response || response.error) {
    alert('Error occurred');
  } else {
    alert('Published to stream - you might want to delete it now!');
  }
});

Will this code post to the user's wall every time they refresh the site?

What should be done in this case?

Answer №1

Who or what is initiating the FB.api request? If it's simply a piece of code enclosed in a script tag, it will execute once the browser reaches that point.

Alternatively, you could consider saving a cookie value or similar after the FB.api call and then verifying it during page load, but this may be unnecessary effort.

Answer №2

Are you looking to limit his post to just once?

If that's the case, you'll need to establish a "state". This can be done either client-side (using cookies) or server-side (with a database).

Start by creating a boolean variable called "posted", and store it in either a cookie or database (cookies might be easier since you're using javascript).

var posted=getCookie("posted");
if(!posted)
{
  //call the FB.api();
  setCookie("posted", true, duration);
}

To learn more about setCookie and getCookie functions, visit http://www.w3schools.com/JS/js_cookies.asp

Answer №3

To determine if a message has already been posted, perform a FQL query on the stream table using your app id. Here is an example:

<!DOCTYPE html>
<html>
<body>
<div id="fb-root"></div>
<a href="#" onclick="postToWall();return false;">Post To Wall</a>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
  FB.init({ appId  : '**yourAppID**', status : true, cookie : true, xfbml  : true });

  function postToWall() {  
    FB.login(function(response) {
      if (response.session) {
        FB.api(
          {
            method: 'fql.query',
            query: 'SELECT post_id, message from stream where app_id = **yourAppID** and source_id = me()'
          },
          function(response) {
            if(response.length == 0){
              FB.ui(
              {
                 method: 'feed',
                 name: 'Facebook Dialogs',
                 link: 'https://developers.facebook.com/docs/reference/dialogs/',
                 picture: 'http://fbrell.com/f8.jpg',
                 caption: 'Reference Documentation',
                 description: 'Dialogs provide a simple, consistent interface for applications to interface with users.',
                 message: 'Facebook Dialogs are easy!'
              },
              function(response) {
                if (response && response.post_id) {
                   alert('Post was published.');
                } else {
                  alert('Post was not published.');
                }
              }
             );         
            }
            else { 
              alert('User already posted this message');
            }
          }
        );
      }
    } , {perms:''}); 
}
</script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble setting the InnerHTML property of Null on my Ionic app, what could be the issue?

I'm working on a code to display the remaining time for generating a random code in the DOM. var count = setInterval(function () { var date = new Date(); var currentSecond = date.getSeconds(); ...

Error in GLSL file: "Module parsing error: Unexpected symbol"

I'm currently working on creating a custom image transition using a shader, and I require a fragment.glsl file for this purpose. However, when I try to import this file into my .js file, I encounter the following error: Compiled with problems: ERROR ...

What could be causing this slider to malfunction in Firefox?

I have recently developed a slider on this page: While the slider functions smoothly in Chrome, I am facing compatibility issues with Firefox. Can anyone shed some light on why this might be happening? Here is the HTML, CSS, and JS code used for the slid ...

After encountering a character with CSS, begin a new line

I have a CSV spreadsheet with data that looks like this: <p>Features:• first feature• second feature• third feature• fourth feature• and so on (the total number of features is variable)</p> I want each feature to display on a new li ...

Here is a guide on how to specify function selection values for a total order. By default, the selection will have predetermined values, and upon clicking the sum button,

<tr id=""> <th> <select id="selection" onchange="myFunction()"> <option id="0" value="0">None</option> <option id="1" value="4.00">Women Suit</option> <option id="2" value="10.00">Dres ...

Is it possible to translate the content of the page into English and French simply by clicking on the designated buttons?

As I dive into working with knockout, I am still in the learning process. Currently, I have a dropdown code where selecting English translates the entire page to English and selecting French translates it to French without any issue. I believe this functio ...

Transforming color images into black and white using JavaScript

     I have implemented this code to convert colored images to grayscale. function applyGrayscaleEffect() {         var imageData = contextSrc.getImageData(0, 0, width, height);         var data = imageData.data;         var p1 = 0.99;   ...

Using PM2 to Manage Your PHP Scripts in Cluster Mode

Currently, I have been effectively managing single instances of PHP daemons with PM2, and so far everything is running smoothly! When it comes to managing Node.js/IO.js apps with PM2, I can easily launch them in cluster mode without any issues. However, t ...

Ways to transmit data from PHP to JavaScript

I have a file called "hotlaps.php" where I've created a JavaScript script: echo "<body onload=\"myFunction(".$array_1.",".$array_2.",".$array_3.");\">"; In my "hotlaps.js" file, I have the following function: function myFunction(arr ...

Configuring .env files for both production and development environments in Node.js

As I observed, there were various approaches to setting up environments in NodeJS - some seemed straightforward while others appeared more intricate. Is it possible to utilize package.json scripts to manage environment variables? If so, what is the best p ...

Unable to invoke the jQuery datetimepicker function within a personalized directive

I have created a unique time picker directive in AngularJS to display a datetimepicker. app.directive("timePicker", function() { return { restrict: "A", link: function(scope, elem, attrs) { / ...

Step-by-step guide on replacing Express API routes with React Router

I am currently working on an application that utilizes React Routes and is served with an Express server. The Express server also contains routes for API calls. Server.js const express = require('express') const path = require('path') ...

In PhantomJS, where is the location of the "exports" definition?

Consider the following code snippet from fs.js: exports.write = function (path, content, modeOrOpts) { var opts = modeOrOptsToOpts(modeOrOpts); // ensure we open for writing if ( typeof opts.mode !== 'string' ) { opts.mode = ...

I'm struggling to grasp the reason behind the error message stating that x is not a function

Can someone help explain why I keep getting the error message "5Style is not a function"? NationalLevelCategoriesChosenList = [ ["5Style", "5MelodyHarmony", "5RhythmTempo", "5TextureStructureForm", "5Timbre"] ], [ [] ]; if (NationalLevelCategoriesC ...

Difference between ng-controller variable and ng-init variable

When working with the code snippet below in angularJS, <script type="text/javascript"> angular.module('app').controller('add', ['$scope',function($scope) { $scope.name = "Bonita Ln"; }]); </script& ...

Node.js and Express causing Openshift to enter a crash loop back-off situation

I've recently ventured into setting up a server for dynamic web pages using Openshift. I put together a basic node.js/Express template solely to establish a connection to Index.html for testing purposes. However, whenever I attempt to execute the code ...

Saving videos for offline viewing in a Vue Progressive Web App with Vue.js 3

I'm having a bit of an issue with my Vue 3 and Typescript setup. I've created a PWA where I display videos, which works perfectly online. However, when I try to access them offline, the videos don't load properly. I have stored the videos in ...

Learn the process of updating a nested document within an array in MongoDB

I have a data structure as shown below: { "name":"xxxxxx", "list":[ { "listname":"XXXXX1", "card":[ { "title":"xxxxxx", "descip":"xxxxxxx ...

AdonisJs experiencing issues with web socket.io functionality

Having trouble with Web socket.io in AdonisJs. I have been using a library called adonis5-scheduler to run tasks within Adonis. Shown below is one of my tasks: import { BaseTask } from 'adonis5-scheduler/build' export default class GetRoulette ...

At times, Express.js may display an error message stating "Cannot GET /"

My objective is to have http://localhost:3000/app display myFile.html and http://localhost:3000/api return "It worked!". I currently have two files set up for this: App.js: const http = require('http'); const fs = require('fs&apo ...