D
D
Dmitry Morozov2017-02-22 19:04:19
PHP
Dmitry Morozov, 2017-02-22 19:04:19

How to get data from Ajax POST json in PHP?

There is Ajax sending:

$.ajax({
                        type: 'POST',
                        dataType: 'JSON',
                        url: '/apiw/',
                        data: this.data,
                        cache: false,
                        context: this
                    })

where this.data is:
JSON.stringify({
                            controller: 'controller',
                            action: 'action',
                            jsonContent: true,
                        });

As a result, the making data is sent: (Ps the CryptoJS.AES cryptor is also used)
{"ct":"5cd5ElvHhiXAQjHvv9xDz1VQRB6UWPPYwYRrskarxm65nGXvrVgjjhg9kSbO7Ec3/Lu/0zpyByhDG1odMbdiruubx5Yfc4oqQSN7scKr0mo:","iv":"b2e7d5affc491a76d507c2e26820b5f6","s":"a94bf91b838c94e7"}

The question is, how to process this array? Using json_decode() writes: Warning: json_decode() expects parameter 1 to be string, object given - json_decode($_POST);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Burov, 2017-02-22
@index1

json_decode(file_get_contents('php://input'));

F
Fuze, 2017-02-22
@InstantMedia

It’s not very clear why such a twist with JSON.stringify, but it’s easier and more logical to do this:

this.data = {
    controller: 'controller',
    action: 'action',
    jsonContent: true
};
$.post('/apiw/', this.data, function(data){
// в data будет объект, если вы в /apiw/ результатом вернёте JSON
}, 'json');

The json type must be specified if the response will be in json.
Accordingly, in PHP in $_POST there will be
array(
    'controller' => 'controller',
    'action' => 'action',
    'jsonContent' => true
);

You can also do it differently:
this.data = {
    controller: 'controller',
    action: 'action',
    jsonContent: true
};
$.post('/apiw/', {param_name: this.data}, function(data){
// в data будет объект, если вы в /apiw/ результатом вернёте JSON
}, 'json');

Then in $_POST will be
array(
    'param_name' => array(
        'controller' => 'controller',
        'action' => 'action',
        'jsonContent' => true
    )
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question