1

I have been trying to catch a variable in an array when an item is clicked on and have been struggling a great deal.

I have a list of items which each have their own name in a database. When the page is loaded these items are listed on the page and can be clicked on to open a new window which displays certain content depending on the items name in the array.

Currently I have managed to get the items names into an array when they are displayed on the page. But when I click on one item the variable used to open the unique window for that item contains every variable in the array (not just the variable name of the item I clicked on).

In my PHP code I go through the database (depending on if isLive == 1) and add each name of the items 'channel_title' into an array named $chName.

$chResult = mysql_query($chSQL);
if ($chResult) {
    $chNum = mysql_num_rows($chResult);
if ($chNum>0) {     

    //Create the arraw
    $chName = array();

    while($row = mysql_fetch_array($chResult)) {

        //Add channel name to array
        $chName[] = ($row['channel_title']);


        if ($row['is_live']=="1") {
            $whatIsLive = "true";
        } else {
            $whatIsLive = "false";
        }

        echo 


         '<li id="'.$row['channel_id'].'" class="list-group-item col-xs-12 col-sm-6 col-md-4 col-lg-3">
                <div class="item">
                    <div class="item-head">
                        <div class="badges">';
                            if ($row['is_live']=="1") {
                                echo '<span class="badge-live">Live</span>';
                            }
                        echo 
                        '</div>
                    </div> 

                    <div class="item-image">
                        <a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'"target="window" onclick="openStreamPopup(); return false;" data-islive="'.$whatIsLive.'" title="'.$row['channel_title'].'">';
                            $activeSSImage = 'userData/'.$row['user_id'].'/channelImages/ss_'.$row['channel_id'].'_t.jpg';
                            $defaultSSImage = 'images/ss_default.jpg';
                            if (file_exists($activeSSImage)) {
                                echo '<img src="'.$activeSSImage.'?rand='.rand(0, 99999999).'" alt="'.$row['channel_title'].'" width="250" height="200">';
                            } else {
                                echo '<img src="'.$defaultSSImage.'" alt="'.$row['channel_title'].'" width="250" height="200">';
                            }
                            echo '<span class="image-cover"></span>
                            <span class="play-icon"></span>
                        </a>
                    </div>

                    </div>
                </div>
            </li>';
    }
} else {
    echo '';
}
} else {
    echo '';
}

In this above code is:

<a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'"target="window" onclick="openStreamPopup(); return false;" data-islive="'.$whatIsLive.'" title="'.$row['channel_title'].'">';

which sends the compiler to a JavaScript function which grabs the array and assigns it to a JavaScript variable - allowing a new window to open with window.open(). This is done with this code:

<script type="text/javascript">

var theChannel = <?php echo(json_encode($chName)); ?>; //Grab the Array $chName - call it theChannel
var windowObjectReference = null; // global variable

function openStreamPopup() {
  if(windowObjectReference == null || windowObjectReference.closed)
  /* if the pointer to the window object in memory does not exist
     or if such pointer exists but the window was closed */

  {
    windowObjectReference = window.open("channels/"+theChannel,
   "window", "resizable,scrollbars,status");  //Open link with theChannel (channel_title) as url

    /* then create it. The new window will be created and
       will be brought on top of any other window. */
  }
  else
  {
    windowObjectReference.focus();
    /* else the window reference must exist and the window
       is not closed; therefore, we can bring it back on top of any other
       window with the focus() method. There would be no need to re-create
       the window or to reload the referenced resource. */
  };

    console.log( "function complete" );
    console.log( theChannel );

}


</script>

The problem I am having is that in this created variable contains every variable of the array. Therefore when I click on an item it adds the URL of each 'channel_title' and not just the 'channel_title' of the item I clicked on.

I have been trying for hours now to get my head around it - I am terrible with PHP and arrays.

The effect I want to achieve is like on http://onperiscope.com/ when you click on a stream and it opens the stream in a new window.

Thank you for your time, please let me know if I have not given enough information.

3
  • 1
    Well, $chName is a PHP array, so when you encode it into JavaScript, you'll get a JavaScript array. So, that's why you're getting every channel in the URL. I don't quite understand how everything works though, so I can't exactly tell you how to fix it. Commented Sep 29, 2015 at 17:59
  • And I'm not quite sure, is there a reason you just can't user the link URL to open in a new window? Commented Sep 29, 2015 at 18:01
  • Thanks for your comment. By new window I don't mean a new tab. The window.open() function allowed me to do this but I couldn't use the JavaScript function inside the PHP. Below ryachza as given an answer that works. Thanks. Commented Sep 29, 2015 at 18:20

1 Answer 1

1

I'm not sure I followed exactly which value you want where, but I think something like this should get you in the right direction:

PHP:

<a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'" target="window" onclick="openStreamPopup(\'' . $row['channel_title'] . '\'); return false;" data-islive="'.$whatIsLive.'" title="'.$row['channel_title'].'">

JavaScript:

function openStreamPopup(theChannel) {
  ...
  windowObjectReference = window.open("channels/"+theChannel, "window", "resizable,scrollbars,status");
  ...
}

So in the PHP you put the "current" value inside the openStreamPopup call as a string (\'' . $row['channel_title'] . '\'), and then that will be available inside your JavaScript function call as the first parameter.

This should get things working, but generally my preference would be to store the contextual value as a data- attribute on the element, bind the onclick event, and inside the handler read the attribute of the triggering element.

Sign up to request clarification or add additional context in comments.

6 Comments

Yes! Perfect answer. I didn't know \ could be used to exit the echo, so that's, great.
Thank you brilliant answer. I will have a look at using data- attribute. Thank you.
@JoeyThomas Glad it worked for you. Regarding the \, that is the escape character within a string. So in PHP if you want to put a single quote ' inside a string, you would use 'some text\'some text'. The echo just takes the string you pass and prints it to the output stream. We want to use the single quote here because you're inside an HTML attribute which is enclosed in double quotes (and it needs to be escaped since you're inside a PHP string using single quotes). This juggling of quotes is one reason why embedding JavaScript inside HTML attributes (like onclick) is not fun.
Yes, it does all seem a bit sloppy. I haven't looked completely into this but would using MySQLi allow for a better design of the code?
@JoeyThomas using MySQLi is certainly good practice, but I don't think it's relevant for the structure here. The issue as I see it is too-tight of coupling between your PHP, HTML, and JS. One thing I would change (and this is just preference) would be to use ?> HTML <?php rather than string concatenation as I think it makes it clearer which pieces are HTML and which are PHP. Then for the JS, I would use something like jQuery (to deal with cross-browser issues) to bind your event on page load rather than embedding JS inside the onclick attribute.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.