Home > Mobile >  Form data from ReactJS AJAX call is not received in PHP
Form data from ReactJS AJAX call is not received in PHP

Time:09-17

Here is my ReactJS code

import React from 'react';
import { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';

const API_PATH = "https://localhost/testapi/contacts/myapi.php"

class Createform extends Component {

  constructor(props){
    super(props);
    this.state={

      Name:"", //initial state of id Name
      Class:"",
      Data_sent:"False"

    };
  }

  handleFormSubmit(event){
    event.preventDefault(); //stops the page from reloading
    // console.log(this.state)
  fetch(API_PATH)
  .then(response =>console.log(response))
  .then(data => console.log(data));

  }

  render() {
    return(
      <div className="App">
        
       <form className="form_temp">
         <label style={{marginRight:"10px"}}>First Name</label>
         <input type="text"  value={this.state.Name} id="Name" onChange={data => this.setState({Name: data.target.value})}></input>
         <br/>
         <label style={{marginRight:"10px"}}>Class</label>
         <input type="text"  value={this.state.Class} id="Class" onChange={data => this.setState({Class: data.target.value})}></input>
         <input type="submit" onClick={e => this.handleFormSubmit(e)} value="Submit" />
        </form>

      </div>
    )
     
  }
}


ReactDOM.render(<Createform/> , document.getElementById("root"));

Here is my PHP rest API code

<?php 

    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
    header("Access-Control-Allow-Headers: Content-Disposition, Content-Type, Content-Length, Accept-Encoding");
    header("Content-type:application/json");
    
    $rest_json = file_get_contents("php://input");
    $data = json_decode($rest_json);
    
    if($data){
        echo json_encode(array("status" => "Success"));
    }
    else{
        echo json_encode(array("status" => "Failed"));
    }

        

?>

When I press the submit button in my ReactJS webpage, I am getting {"status":"failed"} as a JSON response, I don't know why the form data is not going to the PHP API when the submit button is pressed.

I only get the response from...

echo json_encode(array("status" => "Failed"));

...the above statement, but I need the {"status":"success"} response.

CodePudding user response:

You aren't sending any body in your request, which means you also won't receive any, which means if ($data) will never be fulfilled.

It seems you expect the form data to be sent in the request as JSON body. This is not something that will happen automagically, you have to do it yourself.

Take a look at FormData. You can initialize it with a form and it will take the values from the fields. You can then convert the values to an object using entries and Object.fromEntries or by manually iterating over them.

You can then send the data in your fetch call.

const formData = new FormData(theForm)
const formDataObject = Object.fromEntries(formData.entries())

fetch(API_PATH, {
    method: 'POST',
    body: JSON.stringify(formDataObject),
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
    }
}).then( ... )

Note that here I'm referring to a variable theForm which has to be a reference to the <form> element. If you'd change your listener to listen on the submit event of the form and not the click event of the button, you could simply use event.target here.

For more info and a full tutorial, see this and this article.

  • Related