I have this Angular code in a function:
function doAjax() {
$http({
method: 'POST',
url: 'http://thatsmyipv4address/MarkBeacons/www/test.php',
data: {
'dispositivo': getDevice(),
'momentoacceso': getMomentoExacto()
}
})
.then(function (data) {
alert("Data Saved: " + data.response);
console.log(data);
}, function (error) {
//alert('error: ' + error);
console.log('error: ' + error.data);
});
}
And when I call doAjax()
it must send a POST message to my test.php with the values of getDevice()
that returns an String and getMomentoExacto()
that returns another String.
But when I execute the test.php:
$link = mysqli_connect("localhost", "root", "", "markbeacons");
if(isset($_POST['dispositivo'])) {
$dispositivo = $_POST['dispositivo'];
} else {
$dispositivo = 'valor1';
}
if(isset($_POST['momentoacceso'])) {
$momentoacceso = $_POST['momentoacceso'];
} else {
$momentoacceso = 'valor2';
}
echo "$dispositivo";
echo "$momentoacceso";
$sql = "INSERT INTO registroEstimote (dispositivo, momentoconexion) VALUES ('$dispositivo', '$momentoacceso');";
Why it's inserting me on the data base the else values (valor1 and valor2)?
The $http.post and $http.put methods accept any JavaScript object (or a string) value as their data parameter. If data is a JavaScript object it will be, by default, converted to a JSON string.
You have forgotten to add this line
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
$http({
method: 'POST',
url: 'http://thatsmyipv4address/MarkBeacons/www/test.php',
data: $.param({
'dispositivo': getDevice(),
'momentoacceso': getMomentoExacto()
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function (data) {
alert("Data Saved: " + data.response);
console.log(data);
}, function (error) {
//alert('error: ' + error);
console.log('error: ' + error.data);
});
PHP is not populating $_POST as you expect.
The POST-data can be achieved this:
$postdata = file_get_contents("php://input");
To get the correct fields you have to json_decode()
it:
$request = json_decode($postdata);
$dispositivo = $request->dispositivo;
$momentoacceso = $request->momentoacceso;