2

Background

I am embedding tweets with Twitter's Javascript factory function. Documentation here.

This Twitter's Javascript embed function:

    twttr.widgets.createTweet(
      '20',
      document.getElementById('container'),
      {
        theme: 'dark';
      }
    );

Documentation states that an element with DOM ID of 'container' is needed in the document.

    <div id="container"></div>

What I'm doing with this function

The example above provided by Twitter's documentation embeds a tweet that has the id "20". On my page I am embedding the first x amount of tweets about a specific topic using the id's provided in a JSON response from a searchTweets query. The response is stored in $string as json_decoded string.

My problem:

I need to loop through the elements in the JSON response to get the id's of the tweets to put in the twttrwidgets.createTweet function.

I am hardcoding the createTweet function four times currently - the only dynamic bit is creating the elements and DOM ID's to pass in to each of the functions.

Attempt 1: Foreach loop create and increment the ID's

    <?php

    $i = 1;
    foreach ($string as $tweets)
    {
    //echo '<div id="tweet'.$i'" tweetID'.$i'="'$tweets['id']'"></div>';
    ?>

      <div id="tweet.<?php echo $i?>" tweetID.<?php echo $i?>="<?php echo         $tweets['id']?>"></div>
    <?php
    //  echo "<div id='tweet' tweetID='1130852255945486337'></div>"
      $i++;
    }
     ?>

Note I have confirmed that $tweets['id'] gives the id's in the json response as I have tested by simply printing out all $tweets['id'] to the page

The goal is for that loop to create something like this

    <div id="tweet1" tweetID1="123abc"></div>
    <div id="tweet2" tweetID2="123abc"></div>
    <div id="tweet3" tweetID3="123abc"></div>
    <div id="tweet4" tweetID4="123abc"></div>

I understand the way I currently have the loop, it would create as many div's as there were elements in the JSON - that is okay with me for now.

With that I would create the tweets with the follwing code.

    <script>

    window.onload = (function(){

    var tweet1 = document.getElementById("tweet1");
    var id1 = tweet1.getAttribute("tweetID1");

    var tweet2 = document.getElementById("tweet2");
    var id2 = tweet2.getAttribute("tweetID2");

    var tweet3 = document.getElementById('tweet3');
    var id3 = tweet3.getAttribute("tweetID3");

    var tweet4 = document.getElementById("tweet4");
    var id4 = tweet4.getAttribute("tweetID4");

    twttr.widgets.createTweet(
      id1, tweet1,
      {
        conversation : 'none',    // or all
        cards        : 'hidden',  // or visible
        linkColor    : '#cc0000', // default is blue
        theme        : 'light',    // or dark
        align        : 'center'
      })
    .then (function (el) {
      el.contentDocument.querySelector(".footer").style.display = "none";
    });

  //3 more blocks just like twttr.widgets.createTweet(){...} with correct params

This did not work and I can't figure out why. This code works if I hard code in 4 of the id's like I mention in the goal of the loop. Here it is again.

    <div id="tweet1" tweetID1="123abc"></div>
    <div id="tweet2" tweetID2="123abc"></div>
    <div id="tweet3" tweetID3="123abc"></div>
    <div id="tweet4" tweetID4="123abc"></div>

Here is my entire php script. Note this does not include the APIwrapper file included in the beginning and my tokens and keys have been redacted.

    <?php

    //echo "<h2>Simple Twitter API Test</h2>";

    require_once('TwitterAPIExchange.php');

    /** Set access tokens here - see: https://dev.twitter.com/apps/ **/
    $settings = array(
        'oauth_access_token' => "",
        'oauth_access_token_secret' => "",
        'consumer_key' => "",
        'consumer_secret' => ""
    );

    $url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
    $requestMethod = "GET";
    if (isset($_GET['user']))  {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);}  else {$user  = "iagdotme";}
    if (isset($_GET['count']) && is_numeric($_GET['count'])) {$count = $_GET['count'];} else {$count = 20;}
    $getfield = "?screen_name=$user&count=$count";
    $twitter = new TwitterAPIExchange($settings);
    $string = json_decode($twitter->setGetfield($getfield)
    ->buildOauth($url, $requestMethod)
    ->performRequest(),$assoc = TRUE);
    if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}


     ?>


    <?php

    $i = 1;
    foreach ($string as $tweets)
    {
      echo '<div id="tweet'.$i'" tweetID'.$i'="'$tweets['id']'"></div>';
    //  echo "<div id='tweet' tweetID='1130852255945486337'></div>"
      $i++;
    }
     ?>


    <html><body>

    <script sync src="https://platform.twitter.com/widgets.js"></script>

    <script>

      window.onload = (function(){

        var tweet1 = document.getElementById("tweet1");
        var id1 = tweet1.getAttribute("tweetID1");

        var tweet2 = document.getElementById("tweet2");
        var id2 = tweet2.getAttribute("tweetID2");

        var tweet3 = document.getElementById('tweet3');
        var id3 = tweet3.getAttribute("tweetID3");

        var tweet4 = document.getElementById("tweet4");
        var id4 = tweet4.getAttribute("tweetID4");

        twttr.widgets.createTweet(
          id1, tweet1,
          {
            conversation : 'none',    // or all
            cards        : 'hidden',  // or visible
            linkColor    : '#cc0000', // default is blue
            theme        : 'light',    // or dark
            align        : 'center'
          })
        .then (function (el) {
          el.contentDocument.querySelector(".footer").style.display = "none";
        });

        twttr.widgets.createTweet(
          id2, tweet2,
          {
            conversation : 'none',    // or all
            cards        : 'hidden',  // or visible
            linkColor    : '#cc0000', // default is blue
            theme        : 'light',    // or dark
            align        : 'center'
          })
        .then (function (el) {
          el.contentDocument.querySelector(".footer").style.display = "none";
        });

        twttr.widgets.createTweet(
          id3, tweet3,
          {
            conversation : 'none',    // or all
            cards        : 'hidden',  // or visible
            linkColor    : '#cc0000', // default is blue
            theme        : 'light',    // or dark
            align        : 'center'
          })
        .then (function (el) {
          el.contentDocument.querySelector(".footer").style.display = "none";
        });

        twttr.widgets.createTweet(
          id4, tweet4,
          {
            conversation : 'none',    // or all
            cards        : 'hidden',  // or visible
            linkColor    : '#cc0000', // default is blue
            theme        : 'light',    // or dark
            align        : 'center'
          })
        .then (function (el) {
          el.contentDocument.querySelector(".footer").style.display = "none";
        });

      });

    </script>
    </body></html>

I believe the problem is in creating the <div></div> elements dynamically, but I cannot seem to understand why at this point. Am I doing this correctly? I'm sure there is a much more efficient way of doing this, but this seems like it should be working.

My issue is unique to the possible duplicate provided because the issue is not with attaching an event to an ID, rather the actual creation of the ID itself, and my problem is specifically in php.

Gene
  • 104
  • 15
  • 1
    Possible duplicate of [Attach event to dynamic elements in javascript](https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript) – devlin carnate May 28 '19 at 20:47
  • 1
    I don't know but, those elements are outside of `html` – Chay22 May 28 '19 at 23:19

1 Answers1

2

You missed some concat operators in this line.

// What you have
echo '<div id="tweet'.$i'" tweetID'.$i'="'$tweets['id']'"></div>';

// Correct
echo '<div id="tweet'.$i.'" tweetID'.$i.'="'.$tweets['id'].'"></div>';

Also note Chay22's comment about your output being outside the html tags. Everything else is fine.

Tonyeli Tay
  • 411
  • 2
  • 7