Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
quite a noob question, but I tried to use php for the first time and can't get it to work...
I have the most basic php file
echo 'Hello World!';
and I try to fetch the output and alert that. Just for learning how to do that...
My JS code (more or less like
here
):
fetch('./test.php').then(function(response) {
return response.text().then(function(text) {
alert(text);
Both file (test.php and the js file are in the same folder).
Could someone tell me what is wrong here?
Thanks,
celdri
The fetch() method returns a Promise so you can use the then() and catch() methods to handle it:
fetch(url)
.then(response => {
// handle the response
.catch(error => {
// handle the error
In practice, you often use the async/await with the fetch() method like this:
file 1 : readme.php
<?php echo 'Hello World!'; ?>
file 2 : fetch.php
<script type="text/javascript">
async function fetchText() {
let response = await fetch('./readme.php');
console.log(response.status); // 200
console.log(response.statusText); // OK
if (response.status === 200) {
let data = await response.text();
console.log(data);
fetchText();
</script>
echo json_encode($data);
and in js get, i am using axios(https://axios-http.com/docs/intro)
and after console.log(response) and after you can work with response json
Actually, the first comment I got to my answer was correct: It only works on a server/localhost. I seriously didn't know that and I am glad that someone mentioned it! Unfortunately, it seems that the comment has been deleted by some admin. So actually my code was right, I only had to use the absolute path to the php file (though I don't get why)
So php
echo 'Hello World!';
and JS
fetch('./test.php').then(function(response) {
return response.text().then(function(text) {
alert(text);
work.
Thanks everyone,
celdri
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.