Home > Mobile >  JavaScript: Fetch text from php and alert
JavaScript: Fetch text from php and alert

Time:05-29

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

<?php
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

CodePudding user response:

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>

CodePudding user response:

Make sure you are running it on a server, for ex. in local host.

CodePudding user response:

If you mean this.

$data = array("data" => $data);
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

  • Related