1

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>
9
  • Open up the network tab in your browser and try making the call again, this will give you a list of resources being loaded (including backend.php) and you can see what server responses you're getting. Commented Apr 11, 2019 at 21:01
  • 1
    what am i looking for? i see that backend.php is an initiator for a bunch of things but that is it. Commented Apr 11, 2019 at 21:04
  • 1
    got that already Commented Apr 11, 2019 at 21:12
  • 1
    the headers appear to be all empty @DanielG Commented Apr 11, 2019 at 21:13
  • 1
    Chrome browser. Interesting enough, if i add response.text() it prints out the page to the console Commented Apr 11, 2019 at 21:25

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

how do i run it on a server and not though npm
npm run build
2

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
    })

13 Comments

When i run it i get: Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
Looks like you are getting some HTML response there. Can you check in the "Developer tools" usually F12, and check the "Network" tab. For the "backend.php" network interaction you should see the response. Check it's valid json.
its showing my index page as the response. literally a bunch of html like i requested to see view-source.
Right, there is the error. You probably have to find the right way to call backend.php
Check the path to backend.php is correct. It must be at the same level where you triggering the javascript code. Otherwise do something like this fetch('<right-path-to-your-script>/backend.php')...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.