Skip to content
Advertisement

How do I echo posted data from javascript in the php side for development?

I’m using Symfony 5 and I’m posting data from javascript using axios to the php server side. For development purpose, I want the posted data to be displayed on the page so I can better structure and see them.

js file

const onSubmit = () => {
    axios.post('mystuff/post', data)
    .then(response => {
        console.log(response.data)
    })
    .catch(err => {
        console.log(err);
    })
}

php file

/**
 * @Route("/mystuff/post")
 */
public function postData(Request $request)
{
    $post_data = $request->getContent();
    return new JsonResponse($post_data)
}

The above codes works by throwing the data back to the js side and console logging it out, but it is so hard to really see them in the console. So I want something like echoing the data in the controller and displaying them right on the page. How can I do this?

Advertisement

Answer

I just found a react component react-json-pretty that do just that. I just pass in the json response string and it will format it in hierarchy order.

js file

import JSONPretty from 'react-json-pretty';

const App = () => {
    const [jsonString, setjsonString] = useState("");

    const onSubmit = () => {
        axios.post('mystuff/post', data)
        .then(response => {
            setjsonString(response.data);
        })
        .catch(err => {
            console.log(err);
        })
    }

    return(
        <>
            <JSONPretty id="json-pretty" data={jsonString}></JSONPretty>
            <button onClick={onSubmit}>Submit</button>
        </>
    )

}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement