Manpreet Oberoi
Manpreet Oberoi

Reputation: 425

fetch api (GET DATA) from php file

I am trying to fetch values from php file

api.php

      <?php
      // want to fetch this value 
      $a = 'come!! fetch this value';

      ?>

my javascript page has code like this.(this code is not on page api.php)

            fetch('http://localhost/react_task/react-webpack-boilerplate/php/api.php', {
        method: 'get',
        // may be some code of fetching comes here
    }).then(function(response) {
            if (response.status >= 200 && response.status < 300) {
                return response.text()
            }
            throw new Error(response.statusText)
        })
        .then(function(response) {
            console.log(response);
        })

can you please guide me how to fetch value of variable from php file by using fetch.

Upvotes: 6

Views: 25724

Answers (3)

Okechukwu Obi
Okechukwu Obi

Reputation: 519

You should use echo to display it in php then it will be available in you JavaScript reponse.

Upvotes: -1

RickCoxDev
RickCoxDev

Reputation: 165

Your php needs to output the value you want. A simple way to do this is to use echo. For example:

echo 'come!! fetch this value';

Upvotes: 0

MarcHoH
MarcHoH

Reputation: 340

You are not echoing the value, so it won't be send.

<?php
// want to fetch this value 
$a = 'come!! fetch this value';
echo $a;
?>

Upvotes: 4

Related Questions