0

I'm writing a php script that needs to load a 2D array into a js variable as json. First i make the array then use json_encode to turn it into a string. Then I run a small bit of js to get it accessable on the client side. Like so:

$sBaseData = Filters::$sFilterBaseTypeData;
$sBaseData = str_replace('\r',' ',$sBaseData);
$sBaseData = str_replace('\n',' ',$sBaseData);
$sBaseData = str_replace('\t',' ',$sBaseData);

echo <<<HTML
    <script type="text/javascript">
        var validation_data = JSON.parse('$sBaseData');
    </script>
HTML;

Firefox complains about an unexpected character here:

var validation_data = JSON.parse('{"enumeration":{"js":"","msg":""},"date":{"js":" var parts = widget.value.split('-'); var d = new Date(parts[0],parts[1],parts[2]); PASS = (d.getDay()>=1); ","msg":"Invalid date. Please Enter a date in the format: YYYY-MM-DD"},"text":{"js":"","msg":"what did you do?"},"integer":{"js":"if (isNaN(widget.value)) { PASS = false; } else { intVal = parseInt(widget.value); PASS = (widget.value == intVal); } ","msg":"Please enter an integer value"},"decimal":{"js":"PASS = isNaN(widget.value); ","msg":"Please enter a number"},"group":{"js":"","msg":""},"dealer":{"js":"","msg":""}}')

I tried using http://jsonlint.com/ to find out which character was at fault but it says it's all valid and wonderful. I replaced some characters that were causing issues, is there anything else I should be replacing?

Sheena
  • 15,590
  • 14
  • 75
  • 113

3 Answers3

0

Uh...

var parts = widget.value.split('-');

Putting that in a string that uses single quotes will break it. Use a JSON encoder to output your JavaScript literal.

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

The problem is you have ' in your string while you are using ' to quote the string.

If your json string is valid, you don't need to parse it even. The below will work.

echo <<<HTML
    <script type="text/javascript">
        var validation_data = {$sBaseData};
    </script>
HTML;
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Your JSON is valid but in your js code the simple quote closes the parse function's argument.

Try like this:

"date":{"js":" var parts = widget.value.split(\'-\');
mmg666
  • 353
  • 1
  • 12