Caleb
Caleb

Reputation: 621

Fetch call in ReactJS to PHP file returning undefined

When I run a fetch call from within my componentDidMount() method, it returns undefined. The PHP file returns JSON no problem when I run it manually on a server but the call itself is what returns undefined.

    componentDidMount() {
        fetch("backend.php").then(function (data) {
            console.log("Hello");
            console.log(data);
        })
    }

My console says:

App.js:60 Hello
App.js:61 undefined

However if I navigate to backend.php in my browser i get

[{"ID":"0","Name":"Hulk","Publisher":"Marvel","Date":"2019-04-02","Number":"1"},{"ID":"1","Name":"Hulk","Publisher":"Marvel","Date":"2019-04-02","Number":"2"}]

Here is my PHP file

$result_array = array();
/* Create connection */
$conn = new mysqli($host, $username, $password, $dbname);
/* Check connection  */
if ($conn->connect_error) {
     die("Connection to database failed: " . $conn->connect_error);
}
/* SQL query to get results from database */
$sql = "SELECT * FROM Comics ";
$result = $conn->query($sql);
/* If there are results from database push to result array */
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        array_push($result_array, $row);
    }
}
/* send a JSON encded array to client */
header('Content-Type: application/json');
echo json_encode($result_array);
$conn->close();

Due to difficulties figuring this question out I have added this for you guys to see. This is what returns if I tell it it is text using .then(response => response.text()).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="/favicon.ico" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
    <meta name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="theme-color" content="#000000" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="/manifest.json" />
    <!--
      Notice the use of  in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
</head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  <script src="/static/js/bundle.js"></script><script src="/static/js/0.chunk.js"></script><script src="/static/js/main.chunk.js"></script><script src="/main.c69debfe96d2803a0c36.hot-update.js"></script></body>
</html>

Upvotes: 1

Views: 4639

Answers (2)

g-dg
g-dg

Reputation: 283

It appears that you're using npm to compile this, and you have the PHP file in the src directory of the npm project. Try moving the PHP file into the root folder of the project (with the src, public, and build folder) and referencing it as ../backend.php.

Note: if you are using npm start, it won't work as the npm server can't run PHP. You will need to compile it using npm run build and then use a web server that supports PHP.

Upvotes: 2

MarkSkayff
MarkSkayff

Reputation: 1374

When using fetch and using promises with this fetch, you have the chain a couple of things to get the right json like this:

fetch('backend.php')
     .then(response => response.json())
     .then(json => {
          // Do something with your json
     })

Or to debug the response you can do

fetch('backend.php')
    .then(response => response.text())
    .then(text => {
         console.log(text);
         // do something else with the text
    })

Upvotes: 2

Related Questions