0

What I want to do is that only when I click on a div with id="$project['slug']", it will load the iframe inside that div. So, i removed the src attribute from the iframe, and add it on onclick event. I have this in my HTML/PHP:

<div class="box" id="<?=$project['slug']?>" onclick="load_frame();">
    <iframe id="frame_<?=$project['slug']?>" frameborder="0"></iframe>
</div>

Js:

function load_frame() {
    id = location.hash.replace('#', '');
    var source = "<?php echo $project['video']; ?>";
    $('#frame_'+id).attr("src", source);
}

Unfortunately, when I inspect the iframe it shows: src="<?=$project['video']?>" instead of the value that the variable holds. Do you have any idea what i am doing wrong? thank you!

5
  • 2
    are u using external js ??? Commented Dec 26, 2012 at 11:11
  • Seems you mix asp and php syntax. Change = to echo Commented Dec 26, 2012 at 11:11
  • @NipunJain Yes, i am using external js. Commented Dec 26, 2012 at 11:15
  • 1
    Think about what you're doing. A .js file is delivered to the browser as is, not passed through PHP (by default), so there's no way to insert PHP variables into it. Put the video URL into a data attribute instead. Commented Dec 26, 2012 at 11:16
  • @DCoder Thanks so much for the tip! I learned something today :) It works this way too, but i gave accept to Amith for he provided a more complex answer. Thank you! Commented Dec 26, 2012 at 11:30

3 Answers 3

2

jQuery is a client side language and have access only to the DOM elements once they have been rendered. So what you need to do is store $project['video'] variable in a hidden field and then using the id of that field get access to the rendered data.

Also, i noticed that you should use <?php instead of <?

You may try something like this.

<div class="box" id="<?php echo $project['slug']; ?>">
    <iframe id="frame_<?php echo $project['slug']; ?>" frameborder="0"></iframe>
    <input type="hidden" id="<?php echo $project['slug']; ?>" value="<?php echo $project['video']" />
</div>

Then in jQuery do:

$(document).ready(function(){
    $('.box').click(function(){
        var slug = $(this).attr('id');
        var source = $('input#' + slug).val();
        $('iframe#' + slug).attr("src", source);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

oops, forgot to change the iframe statement to use slug var. Updated!
1

add hidden input on html page

 <input type="hidden" id="hidsource" value="<?php echo $project['video']" />

edit your function in js like this

function load_frame() {
id = location.hash.replace('#', '');
$('#frame_'+id).attr("src", $('input#hidsource').val());

}

hope this will work

Comments

0

You might not have the shorthand syntax enabled on the server. Try standard PHP instead:

<?php echo $project['slug']; ?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.