Sillentre
Sillentre

Reputation: 17

PHP URL Variable into Javascript

After discovering why my site doesn't redirect by header command, I found another problem. The problem is that I want put some variables into url redirecting, that is in javascript. That's part of my code:

<?php
    $cost = 200
    $name = 'Bill'
    $url_endpoint = 'https://example.com/item1='.$cost.'&n='.$name.'.html';
    if( !headers_sent() ) {
        header("Location: $url_endpoint");
    }
    else {
?>

    <script type="text/javascript">
        document.location.href="$url_endpoint";   //That's just example what I want
    </script>
    Redirecting to <a href="$url_endpoint">site.</a> //Same here

<?php
    }
    die();
    exit;
   } // ?
?>

Any ideas/tips for beginner?

Upvotes: 0

Views: 79

Answers (3)

Stewartside
Stewartside

Reputation: 20905

Your script just requires a slight amendment on the output of the variable into the Javascript.

You just need to remember that when you close off PHP using ?>, PHP variables are no longer accessible until you open PHP again with <?

You also had one too many closing brackets which could end up causing a PHP error.

<?php
    $cost = 200
    $name = 'Bill'
    $url_endpoint = 'https://example.com/item1='.$cost.'&n='.$name.'.html';
    if( !headers_sent() ){
        header("Location: $url_endpoint");
    }else{
?>
    <script type="text/javascript">
        document.location.href="<?php echo $url_endpoint;?>";
    </script>
    Redirecting to <a href="<?php echo $url_endpoint;?>">site.</a>
<?php
    die();
    exit;
    }
?>

Upvotes: 1

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11576

Use as

<script type="text/javascript">
  document.location.href="<?php echo $url_endpoint"; ?>;   //That's just example what I want
  </script>
  Redirecting to <a href="<?php echo $url_endpoint"; ?>">site.</a>

Upvotes: 0

skywalker
skywalker

Reputation: 826

Use something like this

<script type="text/javascript">
   document.location.href="<?php echo $url_endpoint; ?>";
</script>

when you want to echo variable to html or in your case javascript. But you could find this on the first page of google search, without asking a question... Search a lot before asking.

Upvotes: 0

Related Questions