W
W
WarriorKodeK2018-01-28 23:22:52
PHP
WarriorKodeK, 2018-01-28 23:22:52

How to get JSON from PHP?

Hello. I've been struggling with the problem for about 2 hours, because I don't know PHP, but I need to do the task.
I have a button, when clicked, we get a new user using ajax

const getNewUser = () => {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://randomuser.me/api/', true);
  xhr.onload = () => {
    if (xhr.status === 200) {
      const userData = JSON.parse(xhr.responseText);
      usersInformation(userData);
    } else {
      throw new Error(`Error: ${xhr.status} ${xhr.statusText}`);
    }
  };
  xhr.send();
};

I also have a function that forms an object with data about the user and calls a function to send this data to users.php, in order to then insert the data into an SQL table.
const usersInformation = (user) => {
  const userData = user.results[0],
    obj = {
      name: capitalizeFirstLetter(userData.name.first),
      lastname: capitalizeFirstLetter(userData.name.last),
      city: capitalizeFirstLetter(userData.location.city),
      phone: userData.phone,
      logoUrl: userData.picture.medium,
    };
  postData(obj);
};

const postData = (data) => {
  const stringifyData = JSON.stringify(data);
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '../users.php', true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send(stringifyData);
}

Data is sent
XHR finished loading: POST "http://localhost:8080/users.php"

5a6e2f51a026c220725113.png
But I can't process them no matter how hard I tried.
<?php
$obj = file_get_contents('php://input');
echo($obj->name);
?>

And with the help , I $_POSTalso tried it in no way ((
Tell me how to do it, maybe I'm stupid somewhere?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question