-1

I am passing a JSON object via ajax to my php file. Then I use the function json_encode, and save it to the database.

The problem is, when the JSON object is empty {}, then in PHP it is not an empty object/array, but it is an empty string "".

I need to deserialize it as encoded (empty JSON object), not as an empty string.

What am I doing wrong?

JQUERY:

                    _key = $(this).data('column-name');
                    _temp = {};
                    $(this).find('> .rc-picker-content  > .rc-picker-item').each(function (__index, $__element) {
                        _temp[__index] = {};
                        _temp[__index] = $(this).attr('data-value');

                    });
                    _attr[_key] = _temp; //the variable which is sent via ajax to php

PHP

if (isset($_POST['value']) && is_array($_POST['value'])){
        $_POST['value'] = json_encode($_POST['value']); //this hould be enmpty array not empty string
 }
  • Have you tried converting the string back into an object on server side? Looks like you need some sort of model. – Tanveer Badar Nov 22 '19 at 10:59
  • 2
    Is it possible to see the code? Without it, it is very hard to debug! – Thomas Gregory Nov 22 '19 at 11:20
  • I added the code snippets – rasslstudio Nov 25 '19 at 07:19
  • `_temp[__index] = $(this).attr('data-value');` this line probably makes it an empty string (it overwrites the previous empty object assignment). This said, the code you added does not show the final value being sent to the php backend. Where php will surely give you an empty array/object if supplied with the appropriate json string. https://3v4l.org/GFFDb – Yoshi Nov 25 '19 at 07:29

2 Answers2

0

use the JSON_FORCE_OBJECT option of json_encode:

json_encode($status, JSON_FORCE_OBJECT);

It may help.

Pratham
  • 259
  • 1
  • 8
0

I found a solution.

I convert the object to string before sending it via ajax to my php file.

_temp =   JSON.stringify(_temp);

This solution has already been proposed. I just had to restructure my code.