Search code examples
phpreactjsreduxredux-form

Unable to retrieve POST values in php when submitting react/redux form


I am building a React + Redux app using PHP as backend. I have a simple login form like so:

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';
import {loginUser} from '../actions/index';

class LoginForm extends Component {

    render() {
        const {fields: {username, password}, handleSubmit} = this.props;
        return (
            <form onSubmit={handleSubmit(this.props.loginUser)}>
                <input
                    type="string"
                    placeholder="username"
                    {...username}
                />
                <input
                    type="password"
                    placeholder="password"
                    {...password}
                />
                <input
                    type="submit"
                />
            </form>
        );
    }
}

export default reduxForm({
    form: 'Login',
    fields:['username', 'password']
}, null, {loginUser})(LoginForm);

I am using redux-form to manage the form data handling. I use loginForm (an action creator) to post the data to the php backend like so:

export function loginUser(props) {
    console.log('props', props);
    const request = axios.post(LOGIN_PAGE, props);
    return {
        type: LOGIN_USER,
        payload: request
    }
}

The console.log correctly displays all the data from the login form.

Here is my PHP backend:

if (!is_user_logged_in()) {
    $username = $_POST['username'];
    $username = $username . 'test';
    $password = $_GET['password'];
    $response = array(
        'username' => $username
    );
    wp_send_json($response);
}

Here is the relevant reducer:

export default function(state = INITIAL_STATE, action) {
    switch(action.type) {
        case LOGIN_USER:
            console.log('reducer', action.payload.data);
            return {
                ...state,
                statusCode:action.payload.data,
                user:action.payload.data
            }
    }
    return state;
}

When I log action.payload.data, I get {username: 'test'}, thus indicating that my backend is not getting data from my form. I.e. If I type the username as abc, I should get back abctest, as opposed to test.

Where am I going wrong?


Solution

  • I completely forgot about this question!

    The form is sending JSON to the backend, here is how to retrieve it:

    $inputJSON = file_get_contents('php://input');
    $input = json_decode( $inputJSON, TRUE ); //convert JSON into array
    $username = $input['username'];