0

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

4
  • what is your database datatype for datetime? Commented Apr 1, 2016 at 14:22
  • It is datetime. And the datatpye of value is INT Commented Apr 1, 2016 at 14:26
  • 1
    i believe that when you do a jquery post, you can not send any get variables.. Commented Apr 1, 2016 at 14:28
  • So should i change it to GET? No, it also does not work. Commented Apr 1, 2016 at 14:31

1 Answer 1

1

The jquery code must be like this. If you look at your browser console, you may see some errors. The jquery should be like this:

var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();

newdate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;

$(document).ready(function(){
    var storeValue = 'storeValue';
    var data = gup('temperature', location.href);        
    if(data != undefined){
    yourData = 'func='+storeValue+'&value='+data+'&newdate='+newdate;
        $.ajax({
            data: yourData,
            type: "POST",
            url: "FunctionManager.php,
            success: function(data){
                alert("Data Saved " + data);
            },
            error: function(xhr){
                alert(xhr.responseText);
            }
        });
    }
});

In Functionmanager.php

    print_r($_POST);

    include "$_SERVER[DOCUMENT_ROOT]/SQLCommunication.php";

    header('Content-Type: application/json');
    if(!isset($_POST['func']) || empty($_POST['func'])){
       exit();
    }else{

 $func = isset($_POST['func'])? $_POST['func']: 'storeValue';
 $val = isset($_POST['value'])? $_POST['value']:'';
 $datetime = isset($_POST['newdate'])? $_POST['newdate']:'';

 if($func == 'readValue'){
        echo readValue();
 }elseif($func == 'storeValue'){
        echo storeValue($val, $datetime);
 }
}

In your date field in your table, set datatype as datetime. Hope this may help.

Sign up to request clarification or add additional context in comments.

21 Comments

Doesn't work. I get nothing in my database now. I updated my code.
have you checked your console.
It says nothing. I only get a php error that the index funcis not defined but that is a common php warning. The strange thing is that if i do $_GETinstead of $_POST i don't get these warnings and also my getData function, which returns the latest value from the database, works again. So i don't know if it is right to stick with $_POST
So from where do you get storeValue. It's not included in your questions. var storeValue=$('#somethingmissing').val();
@binaryBigInt it is common to say a GET is used for a SELECT, and a POST is used for an INSERT or UPDATE...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.