1

I am trying to show a different iframe depending on the age of the visitor without a redirection / refresh.

However after verifying the visitors age, the javascript is not being applied correctly, or at all.

I keep ending up with a blank iframe. Someone please take a look at my code below:

<html>
<head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script></head>
<form method="post">
    <input type="date" name="dob"><br>
    <input type="submit" name="submit" value="Verify Age" />
</form>
<?php
$minAge = 18; // You might read this from a file/database.
$minAge *= 3600*24*365.25;  // $minAge in seconds

if(isset($_POST['submit'])){
    $birth_date = strtotime($_POST['dob']);
    $now = strtotime("now");
    $age = $now - $birth_date; // age is in seconds
    if($age > $minAge)
        echo '<script>$("#myiframe").attr("src", "http://URL1.com");</script>';
    else
        echo '<script>$("#myiframe").attr("src", "http://URL2.com");</script>';
} ?>
<iframe id="myiframe"></iframe>
</html>
1
  • 1
    Waiiit... if you do that with PHP, what do you need PHP for? Why not just echo '<iframe src="http://URL1.com"></iframe>';? Commented Apr 6, 2015 at 21:52

2 Answers 2

2

You js is firing before iframe is added to the DOM. You can move your php code (at least rendering, i.e. echo) under the iframe tag or use something like $(document).ready(function(){<...>}). By the way, there is a more elegant way :

<?php
   $minAge = 18; // You might read this from a file/database.
   $minAge *= 3600*24*365.25;  // $minAge in seconds

   if(isset($_POST['submit'])){
      $birth_date = strtotime($_POST['dob']);
      $now = strtotime("now");
      $age = $now - $birth_date; // age is in seconds
?>

    <iframe id = "myiframe"
            src = "<?php echo ($age > $minAge ? 'http://URL1.com' : 'http://URL2.com'); ?> ">
    </iframe>

<?php } ?>
Sign up to request clarification or add additional context in comments.

1 Comment

I never thought of that ! Thanks! :D
0

When your script runs, the DOM does not have the iframe rendered yet. You need to move your iframe above the php code segment that renders the script tag.

Comments

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.