6

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.

3
  • 1
    Simple. In your PHP page, put echo $a; at the end. Then when you fetch the page, it will grab the text content of the page, which is what you echo'ed. Commented Sep 9, 2016 at 14:36
  • Possible duplicate of How to pass variables and data from PHP to JavaScript? Commented Sep 9, 2016 at 14:37
  • no its dubpicate man.. @DavidR Commented Sep 9, 2016 at 14:42

3 Answers 3

4

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;
?>
Sign up to request clarification or add additional context in comments.

7 Comments

if i echo the value .. then definitely it will echo..... that is right .... but i want to see value of $a on javascript page not on api page.
That's not possible, the only thing JavaScript can see is what's been echoed by PHP or what's is served by the webserver.
basically i am working on security app.. if it echo the data.. then its not uite safe..
Can you maybe explain a bit more about it? For now it looks like you need some kind of authentication?
Basically i am working with 2 servers right now,, apache and node .js.... my apache server(php file) contain public key.. and i want to fetch that public key from apache server.. this is basically i am trying to do.. just explained short of bit.... its quite long security procedure on some website.
|
0

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';

1 Comment

i don't want to echo it.. just want to keep it in variable and see the value in javascript page man.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.