PHP not decoding a JSON object created with Javascript. Error ALWAYS returns 4-ThrowExceptions

Exception or error:

I’m trying to create a mapping of key and value pairs in javascript. I create an object and paste it into a hidden textarea, so i can collect it with PHP and decode the object and eventually save it to a database. The data comes in a JSON format, but i’m unable to decode it as a JSON Object in PHP. json_last_error() always returns a 4 and i have no idea why.

Here i fill my onject in Javascript:

finalMapping =  databaseMappingList.reduce(function(finalMapping, field, index) {
    finalMapping [fileMappingList[index]] = field;
    return finalMapping;
  }, {})

which works fine. Then i paste it into a txtarea:

$('#txtarea').val(JSON.stringify(finalMapping ));

i get the following output, when i echo $_POST[“txtarea”]:

{"a":"a","b":"b","c":"c"}

which i assume is a valid JSON string. hen i use json_decode($_POST[“txtarea”]), i get NULL and when i echo json_last_error(), i get 4. hat am i doing wrong?

How to solve:

Try var_dump($_POST['txtarea']); instead of echo for debugging.

Leave a Reply

Your email address will not be published. Required fields are marked *