digdigdoot
digdigdoot

Reputation: 761

POST data to php file via reactjs axios

I am trying to post data to a php file that is two file levels higher relative to the .js file. I am new to reactjs and not entirely familiar with axios so bear with me.

ReactJS code

onSubmit=(e)=>{
    e.preventDefault();
    alert(this.state.username);
    axios.post('../../connections/submit.php',{
      username:this.state.username
    }).then(res=>{
      console.log(res);
    }).catch(error=>{
      console.log(error);
    });
  };

The PHP file in question:

if(isset($_POST) && !empty($_POST)){
    $data = json_decode(file_get_contents("php://input"), true);
    $username = $data['username'];
    print_r($username);
    $conn=mysqli_connect("localhost","root","","jwt_test");
    $sqlOrder="INSERT INTO user(u_id,username) VALUES(NULL,'$username')";
    $conn->query($sqlOrder);
    $conn->close;
};

Is this the correct way of posting the data? I am returned a 404 error code stating that it could not find my file.

My file structure is as so:

-connections
    -submit.php
-src
    -components
        -submit.js

If it helps, I imported axios in my submit.js file instead of in the App.js file. Any advice would be much appreciated. Thanks for reading.

Upvotes: 0

Views: 1183

Answers (1)

digdigdoot
digdigdoot

Reputation: 761

I've got it to work. For the reactjs file, this is the code:

onSubmit=(e)=>{
    e.preventDefault();
    alert(this.state.username);
    //!!! need to stringify the payload before sending it to phpmyadmin.
    var payload = {
      username:this.state.username
    };
    axios.post('http://localhost/connections/submit.php',
    JSON.stringify(payload)).then(res=>{
      console.log(res);
    }).catch(error=>{
      console.log(error);
    });
  };

The receiving PHP file:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");

if(isset($_POST) && !empty($_POST)){
    $data = json_decode(file_get_contents("php://input"), true);
    $username = $data['username'];
    $conn=mysqli_connect("localhost","root","","jwt_test");
    $stmt = $conn->prepare("INSERT INTO user(u_id,username) VALUES(NULL,?)");
    $stmt->bind_param('s',$username);
    $stmt->execute();
    $conn->close;
};

What was needed were the two headers in the PHP file, encoding the payload in JSON , and using another server to receive the payload, in this case, XAMPP was used.

Upvotes: 1

Related Questions