Answer the question
In order to leave comments, you need to log in
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();
};
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);
}
XHR finished loading: POST "http://localhost:8080/users.php"
<?php
$obj = file_get_contents('php://input');
echo($obj->name);
?>
$_POST
also tried it in no way (( Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question