gtilflm
gtilflm

Reputation: 1465

Onclick confirm() not working when echoed by PHP

I'm trying to use a JavaScript confirm() box via the PHP echo below, and it's not working.

echo '<a href="http://sdfsdfs.com?keepThis=true&TB_iframe=true&height=10&width=1200&x=2342342&enter_other_room=2" class="box" TARGET="_self" oncontextmenu="return false;" onclick="confirm(\"Are you sure you want to enter the users\'s Room?\");\">User\'s Room</a>';

What am I missing here?

Upvotes: 1

Views: 177

Answers (2)

generalG
generalG

Reputation: 351

The js CONFIRM() function returns a true or false. You're not checking to see what the user answered.

Here's a generic function that will ask your question and send the user to your URL. Put it in your HTML.

<script>
function myChoice(question,location) {
    var answer = confirm(question);
    if (answer) {
        window.location.href=location;
    }
    else {
        alert("you're staying here!");
    }
}
</script>

You can still use PHP echo() to generate questions and URLs, reusing the same function.

echo '
<a href="#" class="box" TARGET="_self" oncontextmenu="return false;" 
onclick="myChoice(\'Are you sure you want to enter the users Room?\',\'http://sdfsdfs.com?keepThis=true&TB_iframe=true&height=10&width=1200&x=2342342&enter_other_room=2\');">Users Room</a>';

Upvotes: 1

Barmar
Barmar

Reputation: 780994

You can't escape quotes inside HTML attributes, so onclick="confirm(\"...\");" won't work. Put single quotes around the string. And since it's inside a PHP single-quoted string, you need to escape them for PHP.

And since the string contains an apostrophe inside it, you need to escape that for Javascript. You have to double the backslashes to get a literal backslash into the PHP string. And a third backslash to escape it for PHP.

echo '<a href="http://sdfsdfs.com?keepThis=true&TB_iframe=true&height=10&width=1200&x=2342342&enter_other_room=2" class="box" TARGET="_self" oncontextmenu="return false;" onclick="confirm(\'Are you sure you want to enter the users\\\'s Room?\');\">User\'s Room</a>';

Upvotes: 2

Related Questions