Reputation: 271
I am trying to use a php variable in javascript in the following way but its not working. Can anybody let me know what is wrong in the below code
include './connection.php';
$rating[]=$_GET['rating'];
echo '<script>';
echo 'document.getElementById(' .$rating. ').checked = true;';
echo '</script>';
Upvotes: 0
Views: 92
Reputation: 318182
I'm guessing it should be a string, if so you have to quote it
include './connection.php';
$rating = $_GET['rating'];
echo '<script>';
echo 'document.getElementById("' .$rating. '").checked = true;';
echo '</script>'; // ^^ ^^
Upvotes: 2
Reputation: 103
include './connection.php';
$rating = $_GET['rating']; // forget the square brackets, you don't need an array made here
echo '<script>';
echo 'document.getElementById("' . htmlspecialchars($rating) . '").checked = true;';
echo '</script>';
htmlspecialchars makes sure you're not making your site vulnerable to Cross-site scripting. document.getElementById takes a string parameter, so you need to wrap it in quotes.
Upvotes: 0
Reputation: 71384
You are trying to echo an array, rather than a value in the array.
Why define $rating
as an array? Simply do this:
include './connection.php';
$rating=$_GET['rating'];
?>
<script>
document.getElementById('<?php echo $rating; ?>').checked = true;
</script>
<?php
// continue script
You also need to think about addressing the cross-site scripting (XSS) vulnerabilities which you currently have.
Upvotes: 3