Reputation: 5362
I currently have a button when clicked it should open up a new window but I am getting this error: Uncaught SyntaxError: Unexpected token :
. I am using window.open()
$url = "http://www.google.com";
$button .=
'<input type="button" value="Print Timetable" class="printButton" onclick="window.open('.$url.');"/>';
I have noticed that when I use window.open() with no parameters it works but when I pass in the $url
variable all hell breaks loose. I get syntax errors. I've tried http://www.google.com, www.google.com and google.com to no avail!
Thanks for your help in advance!
Upvotes: 0
Views: 688
Reputation: 29160
Because you are missing the single quotes needed to encapsulate the url string.
$url = "http://www.google.com";
$button .=
'<input type="button" value="Print Timetable" class="printButton" onclick="window.open(\''.$url.'\');"/>';
You're adding a layer of string encapsulation. When you pass a string value to a function it must be in quotes, as it is a string.
doSomething('http://www.ibm.com/');
When you are doing this inline in your html, you need to encapsulate the javascript in double quotes so it becomes
onclick="doSomething('http://www.ibm.com/');";
Then, if you want PHP to echo that, or to assign it as variable, you need to enclose all of that in quotes, so you can do
<?php
//encapsulate in double quotes and escape double quotes
echo " onclick=\"doSomething('http://www.ibm.com/');\" ";
//encapsulate in single quotes and escape single quotes
echo ' onclick="doSomething(\'http://www.ibm.com/\'); ';
?>
Any way you break it down you need have 3 string encapsulations embedded in one another, so you must find a way to differentiate between the quotes used in JS and the quotes used in PHP.
Otherwise you would have a problem.
<?php
//Houston We have a problem!
echo " onclick="doSomething('http://www.ibm.com/');\" ";
^ ^ ^ ^
Open Quote Close Quote Open Quote Close Quote
?>
Upvotes: 5
Reputation: 41767
There are a couple of things wrong here:
You have a period character before the equals, eg
$button .=
Should be
$button =
And you need to escape your single quotes:
$url = "http://www.google.com";
$button = '<input type="button" value="Print Timetable" class="printButton" onclick="window.open(''.$url.'');"/>';
Upvotes: 1
Reputation: 2318
I think it suppose to be like this:
$url = "http://www.google.com";
$button .=
'<input type="button" value="Print Timetable" class="printButton" onclick="window.open("'.$url.'");"/>';
window.open() require quote or double quote
Upvotes: 0