mohammad
mohammad

Reputation: 39

Axios doen't send any data to php

I'm using axios in Reactjs to send user's data to php and then create a new user with php,but when I want to send my data it goes empty and my php side gives some error

My react codes

import React, { useReducer } from 'react';
import axios from 'axios';
import UserContext from './userContext';
import userReducer from './userReducer';

  //Register user
const registerUser = async () =>{
    const config = {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
    };


    const response  = await axios.post('http://localhost/react_cms/api/users/user.php' , {message : 'ppp'} , config);

    console.log(response.data);
}

return (
    <UserContext.Provider 
    value={{

        registerUser
    }}>
    {props.children}
    </UserContext.Provider>
);


}

export default UserState;


And my php side codes :

<?php
    $message = isset($_GET['message']) ? $_GET['message'] : 'no';

    $data = array ('message' => $message);

    echo json_encode($data);
?>

The result of this code is :

{message : 'no'}

Upvotes: 1

Views: 385

Answers (1)

Webber
Webber

Reputation: 5514

You have to either change this line

$message = isset($_GET['message']) ? $_GET['message'] : 'no';

into

$message = isset($_POST['message']) ? $_POST['message'] : 'no';

or leave it as it is and send a get request by changing your axios call

from

const response  = await axios.post('http://localhost/react_cms/api/users/user.php' , {message : 'ppp'} , config);

to

const response  = await axios.get('http://localhost/react_cms/api/users/user.php?message=ppp', config);

Please note that the signature of the get method is different than the post method in Axios, as the get method does not require the data parameter.

It's considered good practice to when sending data to store you use the POST verb, whereas if you are retrieving data for a certain identifier, you may use GET.

Have a look at this documentation for explanations of http verbs that axios can utilize: https://restfulapi.net/http-methods/.

Upvotes: 1

Related Questions