0

In a php function I receive a resultset "$pRecord" that can be extracted with extract($pRecords) .. works fine, t.e. I get variables $name , $description... Now I want to pass this resultset to a javascript function this way:

<img onclick='var myObj = .....; myfunc(myObj)'/>

Clicking the image I get the error:

Uncaught SyntaxError: expected expression, got '}'.

My original code is:

$SEG = "var wObj = JSON.parse('".htmlspecialchars(json_encode($pRecord))."'); ";
$OMCsl = "$SEG Segment.showSegmentlanesBox(wObj);";
$Z .= "<img class='segs' onclick='$OMCsl' src='$this->iconpath/segmentlanes.png' title='id=$id'/>";
echo $Z;

Leaving htmlspecialchars away yields the same error.

What's the problem?

Beckermint
  • 13
  • 4
  • Does this answer your question? [json\_encode sparse PHP array as JSON array, not JSON object](https://stackoverflow.com/questions/11195692/json-encode-sparse-php-array-as-json-array-not-json-object) – Alon Eitan Jan 02 '21 at 16:04
  • A little bit: we are one error message further: Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data. It's again the same with and without htmlspecialchars – Beckermint Jan 02 '21 at 16:17
  • No, I think you just need to `$SEG = "var wObj = ". json_encode($pRecord) . "; ";` – Alon Eitan Jan 02 '21 at 16:19
  • I tried again what you suggest, but the error stays. – Beckermint Jan 02 '21 at 16:23
  • The var_dump of $pRecord (shortened): array(44) { [0]=> string(2) "19" ["id"]=> string(2) "19" [1]=> string(1) "3" ["section_id"]=> string(1) "3" [2]=> string(6) "BRANCH" ["subtype"]=> string(6) "BRANCH" [3]=> string(2) "10" ["seq"]=> string(2) "10" [4]=> string(0) "" ["direction"]=> string(0) "" [5]=> string(17) "0.000000000000000" ["start_lon"]=> string(17) "0.000000000000000" [6]=> string(17) "0.000000000000000" ["start_lat"]=> string(17) "0.000000000000000" [7]=> string(17) "0.000000000000000" ["end_lon"]=> string(17) "0.000000000000000" [8]=> string(17) "0.000000000000" – Beckermint Jan 02 '21 at 16:28

1 Answers1

0

Remove htmlspecialchars and quotes around JSON object.

$SEG = "var wObj = JSON.parse(" . json_encode($pRecord) . "); ";
pavel
  • 26,538
  • 10
  • 45
  • 61
  • Sorry, yields error: Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data.Looking at above var_dump line 1 column 2 is the "r" of text: array(44). Right? – Beckermint Jan 02 '21 at 16:34