Ryan
Ryan

Reputation: 141

how can we inject a PHP variable into Javascript

I have a problem with the "windows.location" command in JavaScript. I would like to add the php variable in the link windows.location. How can i do? For example: I would like to transfer user to English page or Vietnamese Page by variable $lang

Here is my code

echo 'window.location="/B2C/$lang/confirm_fone.html"';

and the result in address bar is:

http://10.160.64.4:1234/B2C/$lang/confirm_fone.html

the $lang in address bar cannot be decode?

Upvotes: 0

Views: 414

Answers (6)

Ron
Ron

Reputation: 1336

If you are in php-context:

echo "window.location=\"/B2C/"{$lang}"/confirm_fone.html\";';

If you are in HTML-Context (or better "outer-php-context"):

window.location="/B2C/<?php echo $lang ?>/confirm_fone.html";

Upvotes: 0

Zeemee
Zeemee

Reputation: 10714

Variables are not resolved by PHP in Strings when you use the ' as delimiter. Use " instead (and ' for the javascript command) or concatenate the String using ..

Upvotes: 0

Prabhuram
Prabhuram

Reputation: 1268

You have to concatenate the value, as follows :

echo 'window.location="/B2C/'.$lang.'/confirm_fone.html"';

Upvotes: 0

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

If you put php variables within the string you should use Double Quotes .

echo "window.location='/B2C/$lang/confirm_fone.html'";

Upvotes: 0

Stegrex
Stegrex

Reputation: 4024

This is because the whole string is in single quotes.

You'll want to use double quotes for interpolation.

Otherwise, you can try:

echo 'window.location="/B2C/'.$lang.'/confirm_fone.html"';

Upvotes: 2

Amber
Amber

Reputation: 526703

Variables in single-quoted strings don't get interpolated in PHP.

Use this instead:

echo 'window.location="/B2C/' . $lang . '/confirm_fone.html"';

Or use doublequotes:

echo "window.location='/B2C/$lang/confirm_fone.html'";

Upvotes: 7

Related Questions