Rodrigo Kravetz
Rodrigo Kravetz

Reputation: 382

Creating a Facebook Share Button after Ajax Request

Current Scenario: User logins via Facebook in my website. Immediately after logging in, random content is given to him using Ajax (one happy phrase). This content links to a OpenGraph valid static page (respecting Facebook OpenGraph best practices). At the same time, the Facebook Share popup pops up and he/she can share his happy phrase on Facebook.

Desired scenario by stakeholders (a.k.a. wife):

Share-pop-up should not pop up automatically. A dynamic "fb share button" should be generated with JS, so: user reads happy phrase, user is happy, user clicks share on facebook.

My attempt:

$.getJSON( "ajax/fortune.php?id="+response.id, function( data ) {
   console.log(data);
   $( "#result" ).html( data.message );
   $("#shareButton").html('<div class="fb-share-button" data-href="http://www.-----.com/cookie/'+data.cid+'" data-layout="button_count"></div>');
});

Result: nothing happens. I just need to put that button there.

My plan B would be putting a img button or bootstrap share button with a link to FB sharer.php. But I don't think this would be a nice approach.

Any clues :) ?

RMK: Using jquery 1.11.3

Upvotes: 4

Views: 1461

Answers (1)

Vishnu
Vishnu

Reputation: 12313

You have to render it after adding that.

$.getJSON( "ajax/fortune.php?id="+response.id, function( data ) {
   console.log(data);
   $( "#result" ).html( data.message );
   $("#shareButton").html('<div class="fb-share-button" data-href="http://www.-----.com/cookie/'+data.cid+'" data-layout="button_count"></div>');
   FB.XFBML.parse(document.getElementById('shareButton'));
});

Upvotes: 2

Related Questions