Tom
Tom

Reputation: 4577

Escape quote character within string in Javascript generated with PHP

Not sure if that title makes any sense but I'll try and explain it.

I am generating some content with PHP.

What I am attemtping to generate is a string that will spit out an URL with some JavaScript in the onlick event if the user has JavaScript enabled, and then a regular link if the JavaScript is not enabled.

$url = "<script type=\"text/javascript\">
    document.write(\"<a href='#' onclick='$('#UserID').val(" . 
            mysql_result($recordset, $count, "userid") . "); return false;'>
        Click here
    </a>\");
</script>
<noscript>
    <a href=\"/scripts/updateuser.php?id=" . 
            mysql_result($recordset, $count, "userid") . "\">Click here</a>
</noscript>"; 

The problem I am running into is the jQuery selector for #UserID. Since it's single quoted it bombs out there when clicked and processes the hash mark and goes to the top of the page ignoring the return false.

I can't put double quotes there because that's at the start and end of my document.write statement.

Any ideas on how to structure the string around the jQuery selector here using escape characters or whatever?

Upvotes: 0

Views: 1182

Answers (2)

Marc B
Marc B

Reputation: 360572

Good god that's ugly. Try this on for size:

$userid = mysql_result($recordset, $count, "userid");

$url = <<<EOL
<script type="text/javascript">
    document.write('<a href="#" onclick="$(\'#UserID\').val({$userid})); return false;">Click here</a>');
/script>
<noscript><a href="scripts/updateuser.php?id={$userID}">Click here</a></noscript>
EOL;

I won't get into how 1990's document.write is, but how about this:

<?php
    $userid = ...
?>
<a href="scripts/updateuser.php?id=<?php echo $userid ?>" onclick="$('#UserID').val({$userid}); return false;">Click here</a>

Upvotes: 1

tvkanters
tvkanters

Reputation: 3523

You can use $(\\'#UserID\\'). The double backslash is to make PHP put one extra backslash, making them usable in the onclick attribute. (Besides that, the first comment on the question should be followed rather than using this answer.)

Upvotes: 2

Related Questions