I have a button
onclick="click(' . $item . ');"
then the javascript function is supposed to pass $item to another page. It works fine if $item is a number, but not if it’s a string, and sometimes it’s a mix of characters and numbers which I can’t control.
function click(c)
{
var u = "items.php?serial=" + c;
document.location.href = u;
}
Is there a way to do this in JS?
2
Answers
Try this:
The escaped quotes are what you need.
The problem is that
$item
may contain some content that botches up your functionality. You havebut what if
$item
is O’Brian? In that case this translated toso what actually happens, you are to pass a string to
click
which is O but it will not work. See:You will get a complain about the paranthesis not being closed, because after closing the string O it expects the bracket of the function to be closed, but it gets Brian instead.
Since the suggested
encodeURIComponent
is a Javascript function (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) that you are to run forc
according to the suggestion, it will not resolve your issue by itself. You will need to prevent errors from occurring by adding slashes, likeand then call
encodeURIComponent
inside your JS function, like