简体   繁体   中英

How to retrieve data in PHP, sent from React js using fetch()?

I want to send my form data from the react js application to my back-end PHP program. To send data I'm using the fetch() in react js. The following is my react js code:

import React, { Component } from 'react';

class Form extends Component{
    constructor(props){
        super(props);
        this.state = {
            username:''
        }
    }

    submitHandler = async (event) => {
        event.preventDefault();
        console.log(this.state.username);
        const data = this.state.username;
        await fetch("http://localhost:9090/assign/getApi.php",{
            method:'POST',
            headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({data})
        }).then((res)=>console.log(res));

    }

    render(){
        return(
            <div className="form">
                <form method="POST" onSubmit={this.submitHandler}>
                    <input type="text" placeholder="name" onChange={(event)=>{
                        this.setState({
                            username:event.target.value
                        });
                    }} value={this.state.username} />
                    <input type="submit" value="click" name="submit" />
                </form>
            </div>
        );
    }

}

export default Form;

How do I retrieve this data in my PHP code? Currently, I'm just doing this, but the output is an empty Array()

<?php
print_r($_POST);
?>

You should add a name to your input ex. name="name"

<input type="text" name="name" placeholder="name" onChange={(event)=>{
                        this.setState({
                            username:event.target.value
                        });
                    }} value={this.state.username} />

if you will use fetch then you should path params:

await fetch("http://localhost:9090/assign/getApi.php",{
      method: 'POST',
      headers: new Headers({
                 'Content-Type': 'application/x-www-form-urlencoded',
        }),
      body: "name= " + data

and in php:

<?php

$name = $_POST['name'];
echo $name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM