Search code examples
ajaxjquerygoogle-plus-one

Getting Google Plus button to show after inserting markup with ajax


I'm trying to load a google+ 1 button on a page, the goal is to have the buttons markup inserted into the page via ajax and then make the call for the button to be rendered.

The button renders fine when the page is loaded first time around. The problem arises when the markup is fetched from /displaycode.php and then the render call is made again.

<a href="javascript:void(0)" id="btn">REFRESH</a>
<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
  {"parsetags": "explicit"}
</script>
<script type="text/javascript">
$(function() {
  $("#btn").click(function() {
        $('#live-preview').empty();
        $("#live-preview").load('/displaycode.php #code');
        gapi.plusone.go();
    return false;
  });
    gapi.plusone.go();
});
</script>
<div id="live-preview"><div id="code"><div class="g-plusone"></div></div></div>
</div>

A demo of the problem can be viewed here http://32px.co/googleplusdemo.php . Thanks for any help in advance.


Solution

  • Render method

    Use explicit render: https://developers.google.com/+/plugins/+1button/#example-explicit-render

    gapi.plusone.render('live-preview')
    

    instead of:

    gapi.plusone.go();
    

    Also needs "{"parsetags": "explicit"}" set:

    <script type="text/javascript" src="https://apis.google.com/js/plusone.js">
        {"parsetags": "explicit"}
    </script>
    

    Edit

    You further have to make sure to call render after the jQuery load is complete. So the element is really in the DOM.

    $(function() {
        $("#btn").click(function(e) {
            e.preventDefault();
            $('#live-preview').empty(); // Not necessary 
            $("#live-preview").load('/displaycode.php #code', function() {
                gapi.plusone.render('live-preview');
            });
        });
        gapi.plusone.render('live-preview');
    });