React - Form taken from PHP giving error "CANNOT POST"

Asked

Viewed 42 times

0

Hello, I’m having a problem reusing a form that I used to use in my html application so that I sent the data to a PHP file to insert into my MYSQL database. Unfortunately I am not able to take advantage of this same form in React because there is an error: "cannot post". Could you tell me if it is possible to send a form from an React application to a PHP file for data insertion? Below my code:

import React from 'react';

function Pedidos() {

    return(
        <>
            <div className="row-sm-6" >
                <div className="col" >
                    
                    <form className="col-lg-12" action='http://localhost:8080/React6/fse/src/php/processamento_pedidos.php' method="POST" >

                        <div className="col-12">
                            <input className="form-control" type="nome_cliente" id="nome" name="nome_cliente" placeholder="Nome completo" required />
                        </div>

                        <br />

                        <div className="col-12">
                            <input className="form-control" type="endereco" id="endereco" name="endereco" placeholder="Endereço para entrega" required />
                        </div>

                        <br />

                        <div className="col-12">
                            <input className="form-control" type="email" id="email" name="email" placeholder="Email para contato" required />
                        </div>

                        <br />

                        <div className="col-12">
                            <input className="form-control" type="telefone" id="telefone" name="telefone" placeholder="Telefone para contato" required />
                        </div>

                        <br />

                        <div className = "opcoes_produtos">
                        <label for="">Selecione seu Produto:</label>
                        <select className="form-control" name = "produto">
                            <option value="FOGAO 4 BOCAS">Fogão 4 bocas</option>
                            <option value="FOGAO ATLAS">Fogão ATLAS</option>
                            <option value="MICROONDAS ELETROLUX">Microondas Eletrolux</option>
                            <option value="MICROONDAS PHILCO">Microondas Philco</option>
                            <option value="MICOONDAS CONSUL">Microondas Consul</option>
                            <option value="GELADEIRA BRASTEMP">Geladeira Brastemp</option>
                            <option value="GELADEIRA TRÊS PORTAS">Geladeira três portas</option>
                            <option value="GELADEIRA DODGE">Geladeira Dodge</option>
                            <option value="MAQUINA DE LAVAR ELECTROLUX">Maquina de Lavar Eletrolux</option>
                            <option value="MAQUINA DE LAVAR PHILCO">Maquina de Lavar Philco</option>
                            <option value="LAVADORA DE PRATOS TORPENTE">Lavadora de Pratos Torpente</option>
                            <option value="LAVADORA DE PRATOS ELECTROLUX">Lavadora de Pratos Electrolux</option>
                        </select>
                        </div>
                        

                        <div className = "quantidade_produtos"> 
                        <label for="">Selecione a quantidade:</label>
                        <select className="form-control" name="quantidade">
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                            <option value="10">10</option>
                        </select>
                        </div>

                        <br />

                        <button type="submit" className="btn btn-success"><b>Enviar Pedido</b></button>   
                        <br />
                        <br />

                    </form>
                </div>                    
            </div>
        </>                     
    )   
}
export default Pedidos;
  • The strategy is different with Ajax the form cannot be submitted as traditionally is done.

1 answer

0


The works differently and needs to send information with , not as it is in the question of the traditional way by itself <form>, moreover your form does not store the information relating to each screen item ie the states and this is a mistake in the construction of your code, I will then propose a minimum example so that you can understand:

function Main() {
  const [name, setName] = React.useState('');
  const [sexo, setSexo] = React.useState('');
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log({name, sexo});
  }
  const handleChange = (e, fn) => {
    fn(e.target.value);
  }
  return (  
    <form onSubmit={handleSubmit}>        
      <div>
        Name: 
        <input 
            name="name" 
            value={name} 
            onChange={e => handleChange(e, setName)}
        />
      </div>
      <div>
        Name: 
        <select name="sexo" 
            onChange={e => handleChange(e, setSexo)}>
          <option>Escolha</option>
          <option>Masculino</option>
          <option>Feminimo</option>
        </select>
      </div>
      <div>
        <button>Enviar</button>
      </div>
    </form>
  )
}
ReactDOM.render( <Main />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<div id="root">Carregando ...</div>

in this example type in the fields and then press the button with the label Enviar and receives the values of the form information.

To send to your as an example: POST Request with Fetch API? another example POST Request with Fetch API?.

In your case very specific in the example code:

const handleSubmit = (e) => {
    e.preventDefault();
    let formData = new FormData();
    formData.append('name', name);
    formData.append('sexo', sexo);
    fetch("http://localhost:8080/React6/fse/src/php/processamento_pedidos.php",
       {
            body: formData,
            method: "post"
       }
    );
} 

Reference: How do I post form data with fetch api?

In short: for the thing changes completely of figure, and need to write code that the understand and can provide what it takes to send a set of information from your for your . If you also want to place a form that checks the data entries use React Hook Form which will enable a differential in the way of working with information already previously treated for your .

  • One basic mistake I was making was the door I was sending the form through. React by default uses port 3000, and my Phpmyadmin and Mysql used port 8080. I solved the problem by changing the ports and paying better attention to the direction, which I had renamed the folders. Very Obirgado!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.