-1

I have the code below in a helper function, where I try to redirect the user to a link after an event occurs.

static public function redirect($path)
{       
    echo '<script type="text/javascript">';
    echo 'self.parent.location.href = "$path";';
    echo '</script>';        
}

In my case I call the function as Helper_Popup::redirect("/account/my_addresses") but, of course, it redirects me to a link something/$path. How should I 'embed' the php variable in the above code?

eldarerathis
  • 35,455
  • 10
  • 90
  • 93
dana
  • 5,168
  • 20
  • 75
  • 116
  • Maybe as `echo "self.parent.location.href = '/$path';";` (note leading slash and quote inversal)? Is that what you're after? – DaveRandom Apr 18 '12 at 12:04
  • 1
    http://stackoverflow.com/questions/3446216/difference-between-single-quote-and-double-quote-string-in-php – thwd Apr 18 '12 at 12:04
  • It is impossible to have a php variable in javascript code. That's 2 different languages, having no access to each other variables. – Your Common Sense Apr 18 '12 at 13:21

6 Answers6

2

You have your $path variable encased in single quotes so the variable is being interpreted literally as '$path' and not the actual value of the variable, which is the difference in php between double and single quotes, try this:

static public function redirect($path)
{       
    echo '<script type="text/javascript">';
    echo 'self.parent.location.href = "'.$path.'";';
    echo '</script>';        
}
martincarlin87
  • 10,848
  • 24
  • 98
  • 145
2

The line is incorrect. If you want to use php in Javascript you have to do it so

echo 'self.parent.location.href = "' . $path . '";';

or you can use the double quotes like this

echo "self.parent.location.href = '$path';";

If you use single quotes php will not be executed. But with double quotes php will parse the php code if available and single quotes will write the echo as plain text: "$path"

alphanyx
  • 1,647
  • 2
  • 13
  • 18
  • I personally like the first example more then the second. There is a big chance that your editor will not highlight the $path variable in the second example. – huysentruitw Apr 18 '12 at 12:14
  • @Your Common Sense: that was wrong described you're right. i've corrected it – alphanyx Apr 18 '12 at 13:35
1
echo 'self.parent.location.href = "'. $path .'";';
TerryProbert
  • 1,124
  • 2
  • 10
  • 28
0
echo "self.parent.location.href = '$path';";
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

Try.

echo 'self.parent.location.href = "'. $path .'";';
undone
  • 7,857
  • 4
  • 44
  • 69
-1

add a <?php ?> tag and echo the variable

Example

<script src='<?php echo $var; ?>' </script>
Sudantha
  • 15,684
  • 43
  • 105
  • 161
  • if the "shoprt_open_tag" option is enabled in the php.ini you can also use "=$var?>" for your output – alphanyx Jul 04 '12 at 16:03