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 trialHenzly Meghie
4,707 PointsUsing 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
9,597 PointsFound 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
Courses Plus Student 21,100 PointsYou 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
4,707 PointsI'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?
Jaime Rios
Courses Plus Student 21,100 PointsHello again Henzly. What Gari mentioned, it's exactly what I meant. Here is a video that explains the API concept.
Here is a repository with fetch examples.