Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Henzly Meghie
Henzly Meghie
4,707 Points

Using React how do I fetch data from my PHP backend with the fetch API?

I am building my frontend with reac.js while trying to pull data from my database. The server-side language I am using is PHP. The problem is that I can't seem to retrieve data from a .php file using the fetch API. How do I make that connection from frontend to backend?

2 Answers

Gari Merrifield
Gari Merrifield
9,597 Points

Found the following tutorial that sounds like it may have some of your answers : https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data

I suspect that in your PHP script(s), that you may want to return your answers as JSON.

PS, I think Jamie meant "expose an API", as in, you have a standard way to ask the server for data and a standard way for the server to return your data to the calling client.

Jaime Rios
PLUS
Jaime Rios
Courses Plus Student 21,100 Points

You can use plain old fetch API or axios. You just need to expose and API on the backend that so you can consume it on the Front.

If you are just using react, you can do it on life-cycle methods like componentWillMount or on any other component's method.

If you are using redux for state management, you can check redux-saga.

Henzly Meghie
Henzly Meghie
4,707 Points

I'm not familiar with "expose and API". Right now I have my .php file sitting in the public folder with index.html. When I fetch for that file I don't get a response. Do I have to hold my .php file on another server?