1

I'm using a PHP/MySQL connection to add a search suggestions feature to my site. It's all working except for one piece. My data all contains parentheses in the values, so when I'm trying to pass the returned data to the input field my onclick function fails! code is as follows:

while ($result = $query->fetch_object()) {
            echo '</li><li onclick="fill(\''.$result->name.'\');">'.$result->name.'</li>';
        }

The list populates from the returned search results, but the query returned looks like this:

</li><li onclick="fill('Boire Field&#44; Nashua&#44; NH&#44; US (KASH)');">
Boire Field&#44; Nashua&#44; NH&#44; US (KASH)</li>

Firebug gives me the following:

unterminated string literal
    fill('Boire Field, Nashua, NH, US (KASH)

The ) in the result is prematurely ending the string. How can I escape this out so it will properly call the function?

Chris Patten
  • 129
  • 3
  • 13
  • 1
    See http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-including-escaping-newlines – Brad Apr 19 '11 at 16:29

1 Answers1

1

As the Brad Suggests.. The best way is JSON_ENCODE

while ($result = $query->fetch_object()) {
            echo '</li><li onclick="fill(\''.json_encode($result->name).'\');">'.$result->name.'</li>';
        }
  • I added `json_encode` like your example, but this is all it returns: `onclick="fill('"Boire Field, Nashua, NH, US (KASH)\r"')`. It looks like it added a `\r` but left the parentheses, which still kicks back "unterminated string literal". – Chris Patten Apr 19 '11 at 17:18
  • Aha! I used URLENCODE and it worked! Thanks for the kick in the right direction! – Chris Patten Apr 19 '11 at 17:24
  • What exactly is your value in the "$result->name", is it "Boire Field, Nashua, NH, US (KASH)", if yes, then json_encode should just return `"Boire Field, Nashua, NH, US (KASH)"` – Just a PHP Programmer Apr 19 '11 at 17:34
  • Oh, Okay. You are welcome. I was about to write more example for it :) – Just a PHP Programmer Apr 19 '11 at 17:35
  • By the way for other people reading this it ended up also being a problem with trailing carriage returns (hence the `\r`) in the data set. A simple `trim()` took care of that one. – Chris Patten Apr 19 '11 at 18:43