Leo
Leo

Reputation: 580

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>";
}

Upvotes: 1

Views: 2054

Answers (3)

Leo
Leo

Reputation: 580

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);
    });
});

Upvotes: 0

Josh Moore
Josh Moore

Reputation: 830

If the limit's being passed into the page that you're constructing links on, then you could grab that number through the $_REQUEST variable like you mentioned. You could then write a for loop in the logic in that page to create the number of links that you want. In that loop you could construct something like this to echo the url onto the page:

echo "<a href='page.php?id={$i}&limit=jscriptVar'>{$i}</a>"

Upvotes: 1

Goran
Goran

Reputation: 3410

You did not put the variable correctly into php. With your code you just wrote limit inside a string. You need to connect variable to a string like this:

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

Upvotes: 2

Related Questions