skip to Main Content

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


  1. Try this:

    onclick="click('' . $item . '');"
    

    The escaped quotes are what you need.

    Login or Signup to reply.
  2. The problem is that $item may contain some content that botches up your functionality. You have

    onclick="click(' . $item . ');"
    

    but what if $item is O’Brian? In that case this translated to

    onclick="click('O'Brian');"
    

    so what actually happens, you are to pass a string to click which is O but it will not work. See:

    function click(c)
    {
        var u = "items.php?serial=" + c;
        document.location.href = u;
    }
    <input type="button" onclick="click('O'Brian')" value="something">

    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 for c according to the suggestion, it will not resolve your issue by itself. You will need to prevent errors from occurring by adding slashes, like

    onclick="click(' . addslashes($item) . ');"
    

    and then call encodeURIComponent inside your JS function, like

    function click(c)
    {
        var u = "items.php?serial=" + encodeURIComponent(c);
        document.location.href = u;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search