I am trying to POST a JSON to PHP where it should be decoded and pushed to MySQL database.
This is my JavaScript code.
var dictstring = "{sensorid: \""+ name +"\", x: " +pos.x +" ,y: "+pos.y+"}";
console.log(dictstring);
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
url: "myfile.php",
data: JSON.stringify(dictstring),
success: function(data){
alert('Success');
},
error: function(e){
console.log(e.message);
}
});
And this is my PHP code
<?php
$jsonData = file_get_contents('php://input');
$data_back = json_decode($jsonData);
$unit = $data_back->{"sensorid"};
$x_axis = $data_back->{"x"};
$y_axis = $data_back->{"y"};
// Create connection
$con=mysqli_connect("xxxxxxx:xxxx","xxxxx","xxxx","xxxxxxxx");
// Check
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert Values
$sql_hm = "INSERT INTO xxxx(unit, x_axis, y_axis)
VALUES ('$unit', $x_axis, $y_axis)";
if ($con->query($sql_hm) === TRUE) {
echo "values inserted successfully";
} else {
echo "No data ";
}
?>
I know the PHP part works - I tried POSTing JSON data with contentType: application/json from a REST client app and it works. But when I am trying it with my Javascript code, it isnt POSTing. I can see the "dictstring" string value in console. I cannot see the "Success" alert too. Interestingly, "Success" alert is shown if I remove the dataType: "json" line. But, POSTing is still not happening as I cannot see the values in database.
What am I missing here?