4

I am trying to send data with Axios:

axios.post( url,JSON.stringify({'i': '90'}))
    .then(function (response) {
        console.log(response);
    });

And get it on the server:

var_dump(($this->input->post())); // Returns an array |  $_POST

For the above JSON value, I am getting this response:

array(2) { ["{"i":"90"}"]=> string(0) "" [0]=> string(0) "" }

Without JSON.stringify, the result from var_dump(($this->input->post())); or with $_POST is empty array.

How to send POST request with JSON data with Axios and get it on the server with PHP?

halfer
  • 19,824
  • 17
  • 99
  • 186
gdfgdfg
  • 3,181
  • 7
  • 37
  • 83
  • 1
    Not 100% sure if this solution will work for Axios as well, so I'm not flagging it as a duplicate. But [this answer](https://stackoverflow.com/questions/28602890/retrieve-json-post-data-in-codeigniter/38656283#38656283) might help. – rickdenhaan Dec 30 '18 at 00:44
  • Thx, let me check. – gdfgdfg Dec 30 '18 at 00:52

3 Answers3

3

I had the same problem , finally found that it was because of XSS Filtering , use

   $i = $this->input->post("i",false);

and in axios use so

var formdata=new FormData();
    formdata.append("key",value);

    this.axios.post("http://URL",formdata).then(res=>{})
Book Of Zeus
  • 49,509
  • 18
  • 174
  • 171
2

This is one possible solution, but I think there must be a better way.

JS:

axios.post( url,JSON.stringify({'i': '90'}))
.then(function (response) {
    console.log(response);
});

PHP (CodeIgniter action):

    $requestData = json_decode(file_get_contents('php://input'), true);

    foreach ($requestData as $key => $val){
        $val = filter_var($val, FILTER_SANITIZE_STRING); // Remove all HTML tags from string
        $requestData[$key] = $val;
    }
    var_dump($requestData);

The response:

array(1) { ["i"]=> string(2) "90" }

gdfgdfg
  • 3,181
  • 7
  • 37
  • 83
0

You need to use json_decode:

$json_data = json_decode($this->input->post());
var_dump($json_data);

echo $json_data->i;

or

foreach($json_data as $data){
   echo $data->i;
}
McBern
  • 549
  • 1
  • 4
  • 8