I've been trying to solve the problem for days, I've seen a lot of examples, but it still works:
I am developing an APP in React Native and at the beginning of the session I send the username and password that the user inserts, but when receiving the data in php to carry out the checks, the sent data never arrives.
my js code
const formik = useFormik({
initialValues: initialValues(),
validationSchema: validacionesFormularioIniciarSesion(),
validateOnChange: false,
onSubmit: async (fromValue) => {
setLoading(true);
console.log("Formulario enviado");
const formData = new FormData();
formData.append('var_user', '5658451554132');
formData.append('var_pasw', '5658451554132');
fetch("MI_URL_API", {
method: 'POST',
cache: 'no-cache',
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'x-api-key': '364332437e8474839343854548574874',
'User-Agent' : 'My-App',
}),
body: formData,
})
.then( (response) => response.json())
.then((json) => {
setLoading(false);
console.log(json);
})
.catch(error => {
console.error(error);
setLoading(false);
});
},
});
PHP code to receive the data
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: x-api-key, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Content-type: multipart/form-data; charset=utf-8");
header("Access-Control-Allow-Methods: POST, GET");
header("Allow: POST, GET");
$datos = json_decode(file_get_contents('php://input'),true);
$result = array('code' => "1", 'var_user' => $datos["var_user"], 'var_pasw' => $datos["var_pasw"]);
echo json_encode($result);
?>
Response of the php, that the variables are empty
Object {"code": "1", "var_pasw": null, "var_user": null}
Thank you very much in advance
FormData is an object that is sent with pairs of
variable = valor
, so you should only take the data from$_POST
:If you're just receiving data, it doesn't make sense to add the header with content type
multipart/form-data
, which is also left over in the AJAX request:In fact, you can omit the header with content type ( reference ):
in the php that receives the data, put this to test that it arrives before altering the data