jdecker jdecker - 11 months ago 55
PHP Question

PHP Field Entry On Change With Apostrophe

I have the following form where when the user selects an option from the

the javascript enters it into the "name" field. It's working perfectly except when the option contains an apostrophe it truncates it to only before the apostrophe. I've tried adding the
selectedValue = selectedValue.replace(/'/g, \"\\'\");
to the javascript but it is not helping. Any advice would be appreciated.

#related form objects
echo "<br><br>Name: <input type=\"text\" name=\"name\" id=\"name\" value=\"$name\" size=\"50\">";

echo "<br>Nearby Suggestions: <select name='nearby' id='nearby'>"; $places=file_get_contents('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='.$lat.','.$long.'&key=xxx&radius=80');
$output= json_decode($places,true);
foreach($output['results'] as $place){
echo "<option value='$place[name]'>$place[name]</option>";
echo "</select>";

#script to enter nearby field into name field upon selection
echo "
var x = document.getElementById(\"nearby\"),
selectedValue = x.value;
selectedValue = selectedValue.replace(/'/g, \"\\'\");

Answer Source

You aren't escaping the values that come from your googleapis call. So when you blindly load a value like Jim's Place into your <option> tag, the resulting code is:

<option value='Jim's Place'>Jim's Place</option>

which contains 3 apostrophes and is broken. Convert the values first.

foreach($output['results'] as $place){
  $place_converted = htmlspecialchars($place['name'], ENT_QUOTES);
  echo "<option value='$place_converted'>$place_converted</option>

which correctly generates:

<option value='Jim&#039;s Place'>Jim&#039;s Place</option>