0

i am trying to post data using axios. i can get the api call to work but the problem i have is processing the data on the server side. the normal $_POST paramater in php is empty.

I have the following action

export const UPDATE_CONTENT = 'update_content';

export function updateContent(values) {
    console.log(values);
    let obj = {};
    obj['params'] = values;
    console.log(obj);
    const request = axios.post(`/api/admin/rename/content/management/format/json`,JSON.stringify(values));
    return {
        type: UPDATE_CONTENT,
        payload: request
    };
}

values is a key value object

{content : "<p>html text</p>",id:"21"}

when i post the using like axios.post(url,values); the request parameter is shown as payload and the $_POST on server side is empty.

when i use JSON.stringify, $_POST is not empty but it does not get sent as proper key value pairs on the request. i get the below

Array
(
    [{"id":"21","content":"<p>html text</p>"}
)

so in the server side i have to do $_POST = json_decode(file_get_contents('php://input'), true);

how can i fix this so i dont have to do $_POST = json_decode(file_get_contents('php://input'), true);

luboskrnac
  • 23,973
  • 10
  • 81
  • 92
shorif2000
  • 2,582
  • 12
  • 65
  • 137
  • You might need to read this too, to fix another error that is there on frontend https://stackoverflow.com/questions/47541032/handling-async-request-with-react-redux-and-axios/47588228#47588228. – Shubham Khatri Jan 31 '18 at 13:13

1 Answers1

3

By default, axios serializes JavaScript objects to JSON and hence it can only be read from "php://input" using file_get_contents("php://input"). Check the documentation

If you want to avoid it you can send the data in application/x-www-form-urlencoded format instead

You can do it by using URLSearchParams like

var params = new URLSearchParams();
params.append('content', '<p>html text</p>');
params.append('id', '21');
axios.post(`/api/admin/rename/content/management/format/json`,params);

or you can use the querystring module as follows:

var querystring = require('querystring');
axios.post('/api/admin/rename/content/management/format/json', querystring.stringify({"id":"21","content":"<p>html text</p>"}));

However after fixing this you will need to handle async actions in action creator in client side. Refer Handling async request with React, Redux and Axios? for solving that issue

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400