0

To process a web form asynchronously, jQuery is used to loop through all fields, and the .val() of the field is saved into an array. This array is then sent to a PHP document which processes the data, by using an .ajax call with dataType: 'json'.

When a (text) field contains double quotes ", the PHP receives only the part of the string up to the double quotes. The full string is available in the javascript, so something goes wrong with sending it as JSON over POST?

I'd love to solve this problem and have tried some things, for instance:

field.val().replace(/"/g, '\"');

when saving into the array, but this stops the javascript from executing.

How can I solve this issue?

B_s
  • 3,026
  • 5
  • 32
  • 51

1 Answers1

0

JSON.stringify() will escape double quotes for you.

var data = { test: '"test"' };
console.log(JSON.stringify(data));
// "{"test":"\"test\""}"
kavun
  • 3,358
  • 3
  • 25
  • 45
  • Thanks, and how can I do that in the `.ajax` call? Since the array given to the ajax call is not JSON yet, right? Only `dataType: 'json'` is set. – B_s Apr 15 '16 at 12:49
  • 1
    I think it can be done with [this answer](http://stackoverflow.com/a/12693986/2976720)? At the moment I cannot make changes to test, but when I can I'll update. – B_s Apr 15 '16 at 12:52