Optimal Placement for FB.Event.subscribe

Here is the code I have implemented on my website for the Facebook Like and Share buttons.

The functionality works seamlessly. When I click the Like button, a notification is promptly displayed on my Facebook profile page. Additionally, Facebook automatically generates a preview image of my site logo. The Like counter on my website accurately reflects the interactions.

I am now looking to track clicks on the Like button. As per information from this resource, the code

FB.Event.subscribe('edge.create', function(response) {});
can help achieve this.

Where should I integrate the code

FB.Event.subscribe('edge.create', function(response) {});
within the existing code snippet below?

    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

    <?php

    echo '<div id="fb-root"></div>';

    echo "<script type='text/javascript'>
      window.fbAsyncInit = function() {
        FB.init({appId: 'my_fb_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>";


    echo '<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="" send="true" layout="button_count" width="450" show_faces="false" font="arial"></fb:like>'; 

?>

Answer №1

Based on information from a discussion on Stack Overflow, it seems that the event subscribe code should be placed after FB.init() and before the anonymous function call.

window.fbAsyncInit = function() {
    FB.init({
        appId  : 'sensored-app-id',
        status : true, // check login status
        cookie : true, // enable cookies to allow the server to access the session
        xfbml  : true  // parse XFBML
    });

    /* All the events registered */
    FB.Event.subscribe('comments.add', function (response) {
        // do something with response
        alert("comment added");
    });
};

(function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/fi_FI/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}());

Furthermore, referencing this developer's code example, it appears that they also recommend placing the event subscribe code after initializing Facebook.

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

I am experiencing an issue where I cannot select a row in datatables to transfer the data to a text field in Laravel 5

I am currently working on a web application using Laravel 5.4. There are certain modules where I have a main form that triggers datatables to appear in a modal dialog window (for example: when I click on a search button, the modal window displays datatable ...

Is there a way to consistently trigger the browser.webRequest.onBeforeRequest event in Mozilla Firefox when it is launched via a link?

Hello knowledgeable individuals. I am unable to solve this issue on my own. Here is the add-on I have created: 1) manifest.json: { "manifest_version": 2, "name": "Example", "version": "1.0", "description": "Example", "permissions": [ "tabs" ...

The output of server.address() method in Node.js is ::

My memory serves me right, a few days back it was showing "localhost". I'm puzzled as to what altered server.address().address to now return double colons (::). According to my research, it seems to be returning an IPv6 address (::) because it's ...

Update the jQuery Get function to enable asynchronous behavior

I've recently been tasked with updating some older code to be asynchronous. The code in question is a jQuery GET function that looks like this: jQuery.get("my url", function(data){ //code here }); What steps can I take to convert this to an as ...

Arrange ten objects in each of the four JavaScript arrays in ascending order based on a specific value

model with sample data -> [{ date: '13413413', name: 'asdfasdf', other: 'kjh' }] The getJSON function returns 4 arrays, each containing 10 model objects. array1 = 10 resultsObj sorted by date from newest to o ...

Utilizing Cookies in an AJAX Request for Cross-Domain Communication with Pure Javascript

I am in the process of developing an Analytics application and I'm seeking a method to uniquely identify each user's device. Currently, my approach involves generating a "cookie" from the server side to track all page clicks and interactions thro ...

Enabling drag and drop functionality for elements in Yii2

I am looking to create draggable elements in a Yii2 advanced application. I have tried using PHP and HTML examples similar to http://jqueryui.com/draggable, but so far it has not been successful. Can anyone provide assistance? Below is the code from the vi ...

Are there any disadvantages to utilizing bindActionCreators within the constructor of a React component when using Redux?

I have come across numerous instances where the bindActionCreators function is used within the mapDispatchToProps function as shown below: ... const mapDispatchToProps = (dispatch, props) => ({ actions: bindActionCreators({ doSomething: som ...

How can the vertical scroll bar position be reset in Material-Table when pagination is activated?

Whenever I scroll up or down in my Material-Table, and then switch pages, the vertical scroll bar doesn't reset to the top of the table. Instead, it stays where it was before changing the page, causing confusion for users. The only mention of scroll ...

JavaScript: Collection of Pictures

I've recently begun my journey into HTML and JavaScript by working on a basic website that showcases four images using a for loop. However, upon viewing the website in a browser, I noticed that only the names of the images are displayed, not the actua ...

How can I transfer the database from my live server to my localhost using php?

I have a large SQL database operating on a live server. Whenever a bug arises, my usual process is to manually export the database from phpmyadmin (by viewing the output text), dropping the localhost database, importing the output dump, and then importing ...

Guide to using VueJS for sending a POST request with a JSON array containing data and uploading a File or Picture for each element in the array

I am currently facing a challenge with Axios where I need to send formData from a dynamic Form to PHP. Users should be able to add multiple "persons" along with their respective data and pictures. Below is the format of the data: data: { person:{ ...

REACT performance impacted by slow array filtering

I have a custom listbox feature, where a div holds a vertical list of other div elements. There is also an input field for searching within the list. While it works fine with small data sets, it becomes extremely slow with large amounts of data. In additi ...

"Put Jest to the test by running it with the Express

Currently, I am in the process of learning how to build an API with TypeScript and experimenting with testing it using the Jest framework. When utilizing a basic Express application like app = express() supertest(app) everything works smoothly. However, ...

accessing the session data to retrieve the key for the query

Let me start by explaining my current setup: I am working on a shipping calculator and have successfully implemented the calculator functionality. However, I am facing an issue with retrieving the zip code. The zip code is extracted from session data as ...

What sets apart the use of `function(){}.bind(this)` and `angular.bind(this, function() {})`

Can you highlight the difference between these two code snippets? function Ctrl($scope) { $scope.$watch(function() { return this.variable; }.bind(this), /*...*/); } and function Ctrl($scope) { $scope.$watch(angular.bind(this, functio ...

Having issues with setting up Spatie on a Windows system

I've been working on setting up Spatie/Browsershot for my Laravel project, but even after following all the necessary steps, I keep encountering an error: 'node' is not recognized as an internal or external command, operable program or batc ...

How can I use JavaScript to trigger a button click event inside an iframe element

Is there a way to retrieve the inner HTML contents of a clicked element in an iframe loaded content using JavaScript? This code uses jQuery: var elements = document.getElementsByTagName('iframe'); [].forEach.call(elements, function(elem ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...

Substitute regular expressions with several occurrences by their respective capture groups

I am attempting to use JavaScript to extract only the link text from a string and remove the href tags. The expected behavior is as shown below: <a href='www.google.com'>google</a>, <a href='www.bing.com'>bing</a> ...