Tips for sharing posts and photos using FB.api platform

Can anyone help with my code for posting feed and photos within FB.api?

var requestData = {
    message : data1,
    access_token: response.authResponse.accessToken,
    link : 'http://jonmosley.co.uk',
    description : 'Descriptionhdofh odfoidf  doifo here',
    url : 'https://pbs.twimg.com/media/DL_O7D5V4AApO24.jpg'
};
FB.api('/me/photos/feed', 'post', requestData, function(apiResponse){
if (!apiResponse || apiResponse.error){
        console.log(apiResponse.error);
        alert('Post ID: ' + apiResponse.id);
    }else{
        alert('Post ID: ' + apiResponse.id);
    }
});

Answer №1

Welcome! Here's an example showcasing the use of Facebook API Graph v2.2 for simple social network access:

Let's display some feed information:

function fetchFacebookData(id) {
  $.ajax({
      url: 'https://graph.facebook.com/v2.2/' + id + '/feed?limit=1&access_token=443213172472393|l2IEt1tuyYta_278fR5NAg8V1jI',
      crossDomain: true,
      dataType: 'json'
  }).done(function(json) {
      var data = json.data[0],
          photo = '',
          html = '';
      if (data.picture != null && data.picture != undefined) {
          photo += '<img src="https://graph.facebook.com/' + data.object_id + '/picture" class="media">'
      }
        var url = {
            link: 'https://facebook.com/',
            tag: 'https://facebook.com/hashtag/'
        }
      html += '<div class="post facebook">';
      html += ' <div class="content">';
      html += '     <div class="left">';
      html += '         <i class="fa fa-facebook-official"></i>';
      html += '     </div>';
      html += '     <div class="right">';
      html += '         <div class="top">';
      html += '             <a class="user" href="https://facebook.com/' + data.from.id + '" target="_blank">' + data.from.name + '</a>';
      html += '             <a class="date" href="' + data.link + '" target="_blank">' + relative_time(data.created_time) + ' ago</a>';
      html += '         </div>';
      if (data.message != null && data.message != undefined) {
          html += '         <div class="bottom">';
          html += urltag(data.message, url);
          html += '         </div>';
      }
      html += '     </div>';
      html += ' </div>';
      html += photo;
      html += '</div>';
      $('#feed').append(html);
  });
}

Now, let's proceed to post feed data to the API:

Javascript

var FacebookLike = {
  // This is just an example, avoid using globals
  fbAppId: '{YOUR API}',
  objectToLike: '{YOUR URL}'
}

// More JS functions can be added here
window.fbAsyncInit = function() {
  FB.init({
    appId: FacebookLike.fbAppId,
    status: true,
    cookie: true,
    xfbml: true,
    version: 'v2.3',
  });
};

// Asynchronously load the SDK
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) {
    return;
  }
  js = d.createElement(s);
  js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function login(title, id) {
  FB.login(function(response) {
    if (response.status === 'connected') {
      alert("Logged in successfully. You can share on your FaceBook page.")
      postLike(title, id)
    } else if (response.status === 'not_authorized') {
      alert("Please authorize the application");
    } else {
      alert("Please login to FaceBook and authorize the application");
    }
  });
}

function postLike(title, id) {
  var stats = false;
  FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
      stats = true;
    } else if (response.status === 'not_authorized') {
      var success = confirm("Please click 'Ok' to authorize the application!");
      if (success) {
        login(title, id);
      }
    } else {
      var success = confirm("Please click 'Ok' login to Facebook!");
      if (success) {
        login(title, id);
      }
    }
  });
  if (stats) {
    title = encodeURI(title);
    FB.ui({
          method: 'share_open_graph',
          action_type: '{graph:action}',
          action_properties: JSON.stringify({
              image: '{..thumbnail.png}',
              certificate: "{..object.php?title=" + title + "&id="+id+"}",
            description: "{external description}",
            title: title,
            course: title,
            type: '{YOUR GRAPH OBJECT: OBJECT}'
          })
      },
      function(response) {
        if (response && !response.error_code) {
          document.getElementById('result').innerHTML = 'Success!';
        } else {
          document.getElementById('result').innerHTML = 'Error: ' + response.error_message;
          if (response.error_code == 100) {
            alert('Sorry! The application is not allowed to post on the FaceBook. Please contact support.');
          } else {
            alert('Sorry! The application could not post on the FaceBook. Please contact support.')
          };
        }
      });
}
return false;
}

HTML

<div id="result"></div>

Hope this information is helpful. Best regards.

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

Is there a way to modify the color scheme of the hamburger icon

I'm experiencing difficulties changing the color of a hamburger icon. I've searched for the specific code responsible for the color change, but I haven't been able to locate it. Ideally, I want the color to be white, but on small screens, i ...

How can HTML5 geolocation be utilized to provide real-time latitude and longitude coordinates for integration with the Google Maps API?

I am currently working on a project where I need to dynamically fetch longitude and latitude values from the browser geolocation and then include them in the options array for the Google Maps API. Here is the code snippet I am using: function initMap(){ ...

Collapse dropdown menus upon clicking outside of them

As a newcomer to coding, I'm trying to figure out how to create multiple dropdown menus where each one collapses when you click outside of it. I've been struggling with the code I wrote for weeks now - I want to have 3 dropdown menus but only one ...

Transferring information from server/app.js to Angular-fullstack controller with multer

I'm facing an issue transferring a filename from server/app.js to a controller in client/app/ Currently, I am utilizing Multer for handling file uploads, which is functioning correctly. However, I need to transfer the filename back to the client side ...

Properly segmenting sections into components in Angular

My project has a specific folder structure as shown below: https://i.sstatic.net/7oihC.png In my list-page, I perform operations such as create, update, and delete using modal dialogs. I am considering creating 4 pages for each of these CRUD operations a ...

Tips for transmitting variable values through a series of objects in a collection: [{data: }]

How to pass variable values in series: [{data: }] In the code snippet below, I have the value 2,10,2,2 stored in the variable ftes. I need to pass this variable into series:[{data: }], but it doesn't seem to affect the chart. Can anyone guide me on ...

I am struggling to decide which attribute to use for implementing image swap on mouseover() and mouseout()

I have a problem using jQuery to switch between images when hovering on and off. Here's the code snippet I'm working with: HTML <img class="commentImg" src="images/comments.png" data-swap="images/comment_hover.png" alt=""> jQuery $(" ...

vee-validate remains consistent in its language settings

Having trouble changing the error message in vee-validate, any suggestions on how to fix this? import VeeValidate from "vee-validate"; import hebrew from "vee-validate/dist/locale/he"; Vue.use(VeeValidate, { locale: "he", dictionary: { he: { me ...

Having trouble importing SVG as a React component in Next.js

I initially developed a project using create-react-app with Typescript, but later I was tasked with integrating next.js into it. Unfortunately, this caused some SVGs throughout the application to break. To resolve this issue, I implemented the following pa ...

Creating a conditional property in TypeScript based on an existing type - a comprehensive guide

Imagine if I had the following: type Link = { text: string; link: string; } interface BigLink extends Link { some: number; something: string; else: string; } However, there's a variable that shares all these properties except for the fact ...

Error encountered when attempting to create an index in ElasticSearch due to

I am encountering an issue with the elasticsearch npm module while attempting to create an Index, resulting in a TypeError with the following message: Unable to build a path with those params. Supply at least index The code snippet I am using is as follo ...

Issue with React Material-UI drawer not functioning properly when invoking a child component function from the parent

Here is a piece of code I have for the App.js file: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Child from './child'; class App extends Component { render() ...

Combining JSON parameter and multipart/form-data file in a single request using Vue.js

Is there a way to send both JSON parameters and multipart/form-data files in a single request using Vue, similar to how Postman does it? https://i.sstatic.net/CMi3D.png I've been looking into how to submit "multipart/form-data" from VueJs. What I nee ...

The Vue property or method is unrecognized when utilizing the non-minified version

When I attempted to display the name 'John' using an inline template in a simple Vue example, I encountered the following error message: [Vue warn]: Property or method "name" is not defined on the instance but referenced during render. ...

What is the process for incorporating a Facebook account and friend list into a Pinax Django project?

Looking to start a project using Pinax social project as a base. I'm interested in enabling users to login with their Facebook accounts, not just using Facebook information for signing up on my site, but also importing their existing Facebook friend l ...

Creating JavaScript code using PHP

In my current project, there is a significant amount of JavaScript involved. I'm finding that simply generating basic strings and enclosing them within "<script>" tags may not be the most efficient approach. What are some alternative methods fo ...

How can I utilize data retrieved from $http.get in Vue.js once the page has finished loading?

I'm having trouble figuring out how to trigger a function in Vue.js after an $http.get request has completed. In the example below, I want to automatically select an element of foobar right after the page loads, but it only works when there's an ...

Surprising results when a class is applied using jQuery

Exploring the differences between two fiddles (make sure to run the code on the jsfiddle pages to see the differences clearly). First Fiddle Simple demonstration: $("body").addClass("noScroll"); alert($("body").hasClass("noScroll")); $("body").removeCla ...

Sending a function parameter when registering for an event

I am currently utilizing the jQuery pubsub for creating custom events: (function($) { var o = $({}); $.subscribe = function() { o.on.apply(o, arguments); }; $.unsubscribe = function() { o.off.apply(o, arguments); }; $.publish = fun ...

What are the reasons for transitioning from using <script> includes to npm installs?

I am currently working on a VueJS project where I utilize npm to handle all Vue-related components such as vue-resource, router, and Vuex. However, in my index.html file, I have also included additional scripts like Bootstrap, jQuery, and Tween using scrip ...