Reputation: 39
I'm making a project for my school.
It's a page-source viewer, but I've ran in to a problem..
Using google chrome, I get this error: Uncaught SyntaxError: Unexpected token : main.php:10
HTML:
<html>
<head>
<title>Codeview - See how your code turns out!</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<script>
var url = <?php echo "$url"; ?>
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
console.log(oReq.response);
</script>
<div id="header">
<h2>Codeview</h2>
</div>
<div id="main">
<br>
<h3>Code of <?php echo $url;?>:</h3>
<hr>
<div id="code">
</div>
<iframe id="Code" class="code"></iframe>
</div>
</body>
</html>
PHP:
<?php
function contains($needle, $haystack)
{
return strpos($haystack, $needle) !== true;
}
$url = $_POST['url'];
if (strpos($url, "http://") !== false) {
$url = $url;
} else {
$url = "http://" . $url;
}
?>
I cant find a colon (:) anywhere on line 10 in my code..
What am I doing wrong?
Upvotes: 0
Views: 107
Reputation: 5778
Try adding a semicolon to the end of this line and also wrap the PHP code in quotes:
var url = "<?php echo "$url"; ?>";
Upvotes: -2
Reputation: 2873
Change this:
var url = <?php echo "$url"; ?>
to this:
var url = '<?php echo "$url"; ?>';
Upvotes: 1
Reputation: 353
As a first step you should add quotes to your js var
var url = '<?php echo "$url"; ?>';
Upvotes: 1
Reputation: 227190
You need quotes around strings in JavaScript.
var url = <?php echo "$url"; ?>
This renders as:
var url = http://google.com
That's a syntax error! Try this:
var url = <?php echo json_encode($url); ?>;
That will add the quotes for you.
Upvotes: 2
Reputation: 5967
You need to use quotes when printing into the variable declaration in your JS code:
var url = "<?php echo $url; ?>";
But don't use this code! It is vulnerable to cross-site scripting attacks. To escape the URL in the javascript context, use json_encode
:
var url = <?php echo json_encode($url); ?>; /* this one is safe */
Upvotes: 1
Reputation: 943108
This: var url = <?php echo "$url"; ?>
Will output something like:
var url = http://example.com
Strings in JavaScript need to be quoted. You are also vulnerable to XSS attacks.
Use json_encode
to convert a PHP string to a JavaScript string.
It is also good practise not to depend on semi-colon insertion.
var url = <?php echo json_encode("$url"); ?>;
Upvotes: 9