1

I am fetching JSON data with CORS and I am getting the JSON data in my console successfully. Now I want to display the fetched data with PHP. What are the next steps after the code below to get the fetched data into PHP?

    <script>
        fetch("http://localhost:8000/get_users.php", {
            method: 'post',
            credentials: 'include'
        }).then(response => {
            return response.json();
        }).then(users => {
            console.log(users);
        });
    </script>

I tried to get it in $_POST:

    $posted_data = array();
    if (!empty($_POST['users'])) {
        $posted_data = json_decode($_POST['users'], true);
    }
    print_r($posted_data);

But users is undefined.

Does someone know how to get the fetched JSON users into PHP? Thanks!

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
alexcc
  • 9
  • 1
  • 5
  • I'm a bit confused. The data you're logging is the response *from* the PHP code, and there doesn't seem to be any data that you're posting *to* PHP. Where are you expecting "users" to come from? – IMSoP Oct 20 '21 at 17:52
  • You didn't pass any data ? – nice_dev Oct 20 '21 at 17:52
  • the array $users is in the get_users.php in localhost:8000 and is sent with CORS to localhost:80 as JSON, the JSON then is console logged into console from localhost:80. So data is passed. But I can’t get it back to PHP from JSON… – alexcc Oct 20 '21 at 18:23
  • If you want to fetch the data in PHP (on the server), you shouldn't be using JavaScript (in the browser) to fetch it. See also [What is the difference between client-side and server-side programming?](https://stackoverflow.com/q/13840429/157957) – IMSoP Oct 20 '21 at 18:36

1 Answers1

0

Okay I found a solution that might bring me one good step further. I need to JSON.stringify() my fetched JSON, that was the issue.

UPDATED CODE:

<script>
        fetch("http://localhost:8000/get_users.php", {
            method: 'post',
            credentials: 'include'
        }).then(response => {
            return response.json();
        }).then(users => {
            console.log(users); 
            var users = JSON.stringify(users);
            alert(users);
        });
    </script>
alexcc
  • 9
  • 1
  • 5
  • That's just undoing the action of [the `response.json()` call](https://developer.mozilla.org/en-US/docs/Web/API/Response/json) which converts the JSON string into an object. If you just want the text, you can [use `response.text()` instead](https://developer.mozilla.org/en-US/docs/Web/API/Response/text). Either way, you're still not passing anything to any PHP code, all of this logic is happening in the browser, long after the PHP code ran. – IMSoP Oct 21 '21 at 14:57