4

I tried to JSON.stringify an array to the server like so:

JavaScript:

jQuery.ajax({
    type: 'post',
    url: ajax_url, 
    data: {
       'settings' : JSON.stringify([...]),
       'action'   : [...]
       },
    traditional: true,
    success:function(data) {
        alert("SUCCESS");
    }, 
    error: function(errorThrown){
       console.log(errorThrown); 
   } 
});

But when I tried json_encode it in PHP it returns NULL.

PHP

$param = json_decode($test, true);
var_dump($param); //it retuns NULL

And JSON.stringify array is displayed like this:

{\"uid\":{\"@cdata\":\"6\"},\"board_name\":{\"@cdata\":\"test\"},\"skin\":{\"@cdata\":\"default\"},\"use_comment\":{\"@cdata\":\"\"},\"use_editor\":{\"@cdata\":\"\"},\"created\":{\"@cdata\":\"20160307182421\"}}

What I'm doing wrong?

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
Raye
  • 43
  • 5

1 Answers1

16

Once upon a time, PHP decided it would be a good idea to escape quote marks in GET and POST parameters, to protect unwitting developers from SQL injection vulnerabilities. They called this sorcery, "Magic Quotes".

When PHP saw the error in their ways, they decided to remove this feature, but for WordPress the damage was already done.

WordPress had embraced the magic quotes from earlier versions, and had become dependent on the half-arsed security it provided. To this day, they continue to add-back the quote marks, so that you must explicitly remove them.

TL;DR:

In WordPress, use stripslashes:

$test = stripslashes($_POST['settings']);
json_decode($test, true);
Community
  • 1
  • 1
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • Love the way you worded this haha! – Darren Mar 21 '16 at 01:19
  • 1
    And 1 hour of confusion and messing around with anything I could think of and finally I came upon this answer that ended my sorrow. :) Thank you!! – zpert Dec 07 '17 at 21:26