Reputation: 31
I'm having an issue with a POST request using React Native's fetch. The request works perfectly fine, but the $_POST variables are not appearing at all server side. I've searched around quite a bit before posting, but no dice.
Can anyone point me in the right direction? The code for the fetch request is below.
const dataString = `username=${email}&password=${password}`;
export default function ajaxPost(dataString, url, callback) {
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(dataString)
})
.then((response) => response.json())
.then((responseJson) => {
callback(responseJson);
})
.catch((error) => {
console.error(error);
});
}
How I'm accessing it on PHP:
$data = 'username=' . $_POST['username'] . '&password=' . $_POST['password'];
echo json_encode($data);
I've also tried hardcoding the following:
export default function ajaxPost(dataString, url, callback) {
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'test',
password: 'test123'
})
})
.then((response) => response.json())
.then((responseJson) => {
callback(responseJson);
})
.catch((error) => {
console.error(error);
});
}
Upvotes: 2
Views: 2668
Reputation: 3541
The data does not go to _POST array if sent the way you send it. You can get it on PHP side using
json_decode(file_get_contents('php://input'), true)
Or use FormData
object and remove json headers in js to get the data traditionally (via _POST and _GET).
Upvotes: 1
Reputation: 406
export default function ajaxPost(email,password, url, callback) {
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
user:{
username: email,
password: password,
}
})
})
.then((response) => response.json())
.then((responseJson) => {
callback(responseJson);
})
.catch((error) => {
console.error(error);
});
}
now access the username and password
$_POST['user']['username'], $_POST['user']['password']
Upvotes: 1
Reputation: 36
I am using the same approach and it works for me. Two things you can try
Upvotes: 0