0

I have an application that takes a JavaScript object, turns it into a string using JSON.stringify(), and passes this string in an ajax POST request. The JavaScript object contains various data, including some user input.

After the data is sent via the POST request, it is decoded using json_decode() to be processed as an array. From this point, the data returned from the application is null.

The user input in the description property contains additional double quotes which causes the data to be invalid, I believe.

How can I escape the double quotes that are entered by the user?

Example Data:

{ name: "Susan", title: "Director", description: ""TEST""}

Note: This is a simple example of the data. The actual data has nested objects.

JavaScript:

let obj = this.objData,
json = JSON.stringify(obj)

$.ajax({
    method: 'post'
    url: url,
    data: {
       method: 'submit',
       form_data: json
    }
});

PHP:

$action=$_POST['method'];

$data=$_POST['form_data'];
$data=str_replace('\"','"',$data);
$data=str_replace("\'","'",$data);
$data=json_decode($data,true); // returns null
CaraPilar
  • 41
  • 1
  • 1
  • 6
  • well, without surprise, your sample data ***is*** invalid json (www.jsonlint.com) – YvesLeBorg Oct 17 '19 at 19:34
  • Is your PHP code not replacing those double quotes? I think it should only allow alpha characters and no special characters. see [Link](https://stackoverflow.com/questions/5199133/function-to-return-only-alpha-numeric-characters-from-string) – Deleted Oct 17 '19 at 19:50
  • 1
    `json_decode` will replace the \" to " and \' to ', so you're not in need to do it, and its what cause the problem, you're ruining the JSON string before decoding. Just remove `str_replace` lines and your code will work perfectly. – Mohammed Alhanafi Oct 17 '19 at 19:53
  • @MohammedAlhanafi - Yea, I tried removing the str_replace lines before and still no luck :-( – CaraPilar Oct 18 '19 at 11:58
  • @CaraPilar did you still have the problem? have you tried my answer? – Mohammed Alhanafi Nov 02 '19 at 16:25
  • @CaraPilar I am facing the same issue. Did you get the solution? – Pranav Vaidya Nov 30 '22 at 07:29

0 Answers0