Search code examples
phpjavascripturlvariableshref

Create a href url with php variable + javascript variable


I'm creating links with Mysql+PHP looping, but I need to add a javascript var into url href, like:

The javascript var is in a jquery cookie: $.cookie('limit')

urls.php:

<a href='page.php?id=1&limit=$.cookie('limit')'>1</a>
<a href='page.php?id=2&limit=$.cookie('limit')'>2</a>
<a href='page.php?id=3&limit=$.cookie('limit')'>3</a>

Put the javascript var into a hidden input doesn't work on this case.

In my page.php I need to use both vars (id and limit) on a mysql query. So insert this javascript var in a hidden input in page.php won't work anyway.

I tried to remove limit var from href url and add this on my page.php but it didn't work:

if(!empty($_REQUEST['limit']){
    $_REQUEST['limit'] = "<script type='text/javascript'>document.write($.cookie('limit'))</script>";
}

Solution

  • Change links to this:

    <a href='page.php?id=1' class='changeMe'>1</a>
    <a href='page.php?id=2' class='changeMe'>2</a>
    <a href='page.php?id=3' class='changeMe'>3</a>
    

    Add a javascript like this:

    $(document).ready(function(){
        $('a[class="changeMe"]').each(function(){
            var newHref = $(this).attr("href") +"&limit="+ $.cookie('limit');
            $(this).attr("href", newHref);
        });
    });