Search code examples
jquerydynamichref

jquery dynamic href based on user_id


I have typed up this little Jquery to dynamically append the href of my billing page based on the users id.

It doesn't seem to be working tho? Hopefully someone can point out my mistake.

Thanks in advance for your help and code snippets.

$individualpage="billing".$_SESSION['user_id'].".php";
$("a#billing").attr("href", "$individualpage");

Link on page

<a href="" id="billing">billing</a>

Solution

  • You're mixing JavaScript (a client-side language) with PHP (a server-side language). Remember that PHP is done by the time JavaScript begins.

    With that said, try something like this:

    Somewhere in your PHP page:

    <?php
      $individualpage="billing".$_SESSION['user_id'].".php";
    ?>
    

    Then, within the HTML of the page, use PHP to dump the value to JavaScript so it can pick up and complete the request:

    $('a#billing').attr('href','<?= $individualpage; ?>');
    

    Although, you're probably better off just dumping it directly in to the <a> tag:

    <a id="billing" href="<?= $individualpage; ?>" ... >...</a>
    

    (And skipping JavaScript altogether.)