i want to store a value in a database with PHP. I call a PHP-function with AJAX.
I check on document.ready() if the website was called with a parameter called temperature:
$(document).ready(function(){
var data = 5; //gup('temperature', location.href);
if(data != undefined){
var sendData = 'func=storeValue&value=' + data + '&datetime=' + getDateTime();
$.ajax({
data: sendData,
type: "POST",
url: "FunctionManager.php",
success: function(data){
alert("Data Saved " + data);
},
error: function(xhr){
alert(xhr.responseText);
}
})
}
}
I use a the php file "FunctionManager" to call the according function which i determine with the passed parameters. So i pass dataand datetime. My FunctionManager looks like this:
<?php
include "$_SERVER[DOCUMENT_ROOT]/SQLCommunication.php";
header('Content-Type: application/json');
if(!isset($_GET['func']) && empty($_GET['func'])){
exit();
}
if($_POST['func'] === "readValue"){
echo readValue();
}elseif($_POST['func'] === "storeValue"){
echo storeValue($_POST["value"], $_POST["datetime"]);
}
?>
So as you can see i first check which function is called and then call the function itself with parameters. I know that this works because i have a new row in my database after calling the website with a parameter. But the fields datetime and value are always zero.
My storeValue- function is located in SQLCommunication.phpand looks like this:
function storeValue($val, $datetime){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
//$datetime = date_default_timezone_get();
//$datetime = '2016-01-04 00:18:00';
$sql = "INSERT INTO tempvalues (datetime, value) VALUES ('$datetime', '$val')";
$conn->query($sql);
$conn->close();
}
This is the function i use to read the temperature parameter:
function gup( name, url ) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url ).toString();
return results == null ? null : results[1];
}
Do you have any ideas which mistake i made? Thanks
datetime. And the datatpye ofvalueisINTGET? No, it also does not work.