-1

I have the following code: opener.postConditionPostCure("<?php echo the_field('cure_description'); ?>")

In some cases the_field() returns ' " ) characters. I believe these characters are throwing errors. I have tried using the js fn escape() function as well as the php fn rawurlencode() as:

opener.postConditionPostCure(escape("<?php echo the_field('cure_description'); ?>"))
opener.postConditionPostCure("<?php echo rawurlencode(the_field('cure_description')); ?>")

to no avail.

I would like the entire string returned by the_field() to be passed to the postConditionPostCure function.

All advice is appreciated. Thanks in advance.

bob
  • 227
  • 3
  • 17
  • Encode it as JSON. [Pass a PHP string to a JavaScript variable (and escape newlines)](http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-and-escape-newlines) – Jonathan Lonowski Oct 12 '14 at 04:58
  • "not working" is the most useless feedback. – Mulan Oct 12 '14 at 05:20
  • Why are you [asking the same question](http://stackoverflow.com/questions/25793124/how-to-deal-with-illegal-characters-in-javascript-function-parameters) again ? – Mulan Oct 12 '14 at 05:46

2 Answers2

1

Use the PHP function addslashes() which will escape those characters that are causing chaos in js.

opener.postConditionPostCure("<?php echo addslashes(the_field('cure_description')); ?>")
brian
  • 2,745
  • 2
  • 17
  • 33
1

This is horrible.

Never ever, ever, ever integrate dynamic output directly into javascript like that.

Read the plethora of reasons why this is a terrible practice here.


But since you're just going to do it anyway, at least encode the JavaScript value properly first.

var json = '<?php echo json_encode(the_field("cure_description"), JSON_HEX_APOS) ?>';

var cureDescription = JSON.parse(json);

opener.postConditionPostCure(cureDescription);

I'm calling json_encode with the JSON_HEX_APOS flag because I'm wrapping the JSON in ' (single quotes) in the JavaScript.


You have two other more ideal options at your disposal though

  1. use ajax to get the value you need
  2. render a <input type="hidden"> and fetch the value using JavaScript.

Both solutions avoid embedding PHP directly in your JS.

Community
  • 1
  • 1
Mulan
  • 129,518
  • 31
  • 228
  • 259