Home > front end >  Combining PHP into a Javascript?
Combining PHP into a Javascript?

Time:10-01

Basically I'm struggling adding PHP into

<a style="cursor:pointer;" onClick="location.href='https://www.example.com/go/'">LINK</a>

My code right now:

        <a style="cursor:pointer;" onClick="location.href='https://www.example.com/go/
                                            
<?php $randomid = rand(361, 370);
echo '' . $randomid . '&name=john'; ?>

        '">Link</a>

But the above doesn't work. When you click, nothing happens.

I have also tried this way:

<?php $randomid = rand(361, 370);
echo '<a style="cursor:pointer;" onClick="location.href='https://www.example.com/go/' . $randomid . '&name=john'">Link</a>'; ?>

But since the javascript contains '' they confict with PHP's html code ''.

How do I solve this?

CodePudding user response:

So ... :) like this - you either use href or use a function onclick... not supposed to be together but this will work:

$randomid = rand(361, 370);?>
<a href="https://www.example.com/go/<?php echo $randomid;?>&name=john" style="cursor:pointer;">Link</a>

From what I read in the comments you are looking for a js function... not an a href link eh?

So how about this:

<?php
$randomid = rand(361, 370);?>
<a onclick="myFunction('<?php echo $randomid;?>');" style="cursor:pointer;">Link</a>
<script type="text/javascript">
    function myFunction(randomid){
        window.location.assign("https://www.example.com/go/" randomid "&name=john");
    }
</script>

CodePudding user response:

Either you can use this one it's also working.

<?php
    $randomid = rand(361, 370);
    echo '<a style="cursor:pointer;" href="https://www.example.com/go/'.$randomid.'&name=john">Link</a>';
 ?>
  • Related