A
A
Alexander Sobolev2018-08-16 13:28:39
PHP
Alexander Sobolev, 2018-08-16 13:28:39

How to get and process JSON in PHP?

I am writing an ajax post request to another server\domain with json data.

jQuery.ajax({
     url: url,
     type: 'POST',
     data: {	action: "get_genres"	},
     dataType: 'json',
     contentType: 'application/json',
     json: true
    })
    .done(function(data){ console.log(data); });

The handler has swich on action.
switch (json_decode($_POST['action'])) {	case 'get_genres': get_genres();break;  }

But the action is empty. I can't view var_dump because the request is "fully ajax". For type checking:
if(!empty($_POST['data'])) { echo json_encode('true'); } else { echo json_encode('false'); }

if(!empty($_POST['action'])) { echo json_encode('true'); } else { echo json_encode('false'); }

returns false
C json-th I encounter not often.. how to parse $_POST and take out $_POST['action'] ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-08-16
@san_jorich

Since you want json - then send json: And on the server instead it will be
data: JSON.stringify({ action: 'get_genres' })
json_decode($_POST['action'])

json_decode(file_get_contents('php://input'), true)['action']

R
Roman Terekhin, 2018-08-16
@RomaZveR

jQuery.ajax({
     url: url,
     type: 'POST',
     data: {	action: "get_genres"	},
     dataType: 'json'
    })
    .done(function(data){ console.log(data); });

switch ($_POST['action']) {
   case 'get_genres': 
       get_genres();
       break;  
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question