0

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>';
3
  • If you enable error reporting you should get a message telling you what is going on. Same as when you inspect the rendered html Commented May 13, 2014 at 19:37
  • Remove the brackets from $rating on the second line. Commented May 13, 2014 at 19:37
  • try doing echo 'document.getElementById("' .$rating. '").checked = true;'; Commented May 13, 2014 at 19:37

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If we're optimizing, why bother setting $rating at all? Just do <?=$_GET['rating']?>.
@Wogan Yes. One could do that, but really $rating should be sanitized before echoing it back out.
2

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>'; //          ^^            ^^

Comments

0
    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.

1 Comment

Should probably link to the english wikipedia ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.