user3541562
user3541562

Reputation: 271

PHP variable inside javascript

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

Answers (3)

adeneo
adeneo

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

Khub
Khub

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

Mike Brant
Mike Brant

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

Related Questions