1

I am using react js on localhost:3000 and I am using PHP on localhost:8080,now I wanted to fetch mysql table data through AXIOS API to the react js page named DataandForm.jsx. I have a PHP page index.php where i am fetching MYSQL table rows which runs on localhost:8080/data/index.php, Now how can I take that data available in index.php to DataandForm.jsx using AXIOS?

DataandForm.jsx

import React from 'react'

class DataandForm extends React.Component{
    constructor()
    {
        super()
        this.state={
            row:[]
        }
    }

    componentDidMount()
    {
        const axios = require('axios');

        // Make a request for a user with a given ID
        axios.get('http://localhost:8080/data/index.php')
          .then( response =>{
            // handle success
            console.log(response);
            this.setState({row:response.data});
          })
          .catch(function (error) {
            // handle error
          console.log(error);
          })
          .then(function () {
            // always executed
          
          });
        
    }
    
    render()
    {
        return(

<div className="container">
    <div className="row">

        <div className="col-sm-6">
           {this.state.row.map(datum=> 
            <div className="row">
                <div className="col-sm-4">key={datum.id}</div>
                <div className="col-sm-4">data1={datum.data1}</div>
                <div className="col-sm-4">data2={datum.data2}</div>
            </div>


            
            )}
        </div>

    <div className="col-sm-10 offset-sm-2"><br/>

<form class="form-inline" action=" " method="post" >
<div class="form-group">
  <label for="email">FIRSTNAME:</label>
  <input type="text" name="data1" class="form-control" id="email" />
</div>
<div class="form-group">
  <label for="pwd">LASTNAME:</label>
  <input type="text" name="data2" class="form-control" id="pwd" />
</div>
 
<button type="submit" class="btn btn-danger">Submit</button>

</form>

</div>
    </div>
</div>

        )
    }
}
export default DataandForm

index.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydata";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}



$sql = "SELECT * FROM datum";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "DATA1: " . $row["data1"]. " - DATA2: " . $row["data2"]. "<br>";
  }
} else {
  echo "0 results";
}

?>

Here, I have an index.php page that just fetches some rows from the table and it runs on http://localhost:8080/data/index.php . I have also a DataandForm.jsx file that's trying to fetch the data from the PHP file using the AXIOS api.

I wanted to fetch rows from table to react front end through php with an api call. Should I make the fetch rows to a json then bring to react? How can I make this happen?

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • I believe you might have encountered the CORS issue. – Salim Ibrohimi Jul 04 '20 at 09:28
  • When you post a bunch of code, it's always helpful to let us know what actually happens whey you run it. What does your `console.log(response)` give you? Do you get the expected result (that you output in PHP)? Do you have any errors in the browser console? – M. Eriksson Jul 04 '20 at 09:30
  • DatafromForm:1 Access to XMLHttpRequest at 'http://localhost:8080/data/index.php' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. This is the error shows in the console – Farhan Shaikh Jul 04 '20 at 09:33
  • Does this answer your question? [No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API](https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe) <- Ignore the "REST API" part, the issue/solution is still the same. – M. Eriksson Jul 04 '20 at 09:36
  • No I guess, I am New to the API. I fetched some data from json placeholder with no issues . here I have not used any JSON . I know I am doing wrong but I am not sure what to do with this. – Farhan Shaikh Jul 04 '20 at 09:40
  • Your issue and the solution is explained in the link above. It's a about localhost:3000 (your javascript) making calls to localhost:8080 (your PHP, which is considered different hosts because of the different ports). – M. Eriksson Jul 04 '20 at 09:45
  • Ok . Let me try the same .Thank You – Farhan Shaikh Jul 04 '20 at 09:51

1 Answers1

0
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE,PATCH,OPTIONS');

Put this at the top of your PHP file to avoid the cors issue..