0

i try to call a php function with Ajax. This is my JavaScript code in my html file:

<script type="text/javascript">
    function ajax(){
        $.ajax({
            type:"POST",
            url: "SQLCommunication.php",
            dataType: "JSON",
            success : function(json){
                json = jQuery.parseJSON(json);
                alert(json.value);
            }
        }
        )
    }

    $("#btn_refresh").click(function(){
       ajax(); 
    });
</script>

I don't know if i have to specify which PHP function i actually want to call? I also don't know how i do that.

My PHP function:

header('Content-Type: application/json');
function readValue(){
    $conn = establishConnection();
    if($conn->connect_error){
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT datetime, value FROM tempvalues";
    $result = $conn->query($sql);

    if($result->num_rows > 0){
        $row = $result->fetch_assoc();
        $arr["datetime"] = $row["datetime"]; //return datetime and value as array
        $arr["value"] = $row["value"];
        if(is_ajax()){
            return json_encode($arr);
        } else {
            return $arr;
        }
    }

    $conn->close();
}

So the problem is now, that nothing happens if i press the button.

5
  • 1
    try print_r(json_encode($arr)) Commented Mar 31, 2016 at 20:48
  • You need to invoke the readValue() function in your PHP code and echo its result. Commented Mar 31, 2016 at 20:49
  • And you don't need to call parseJSON as I know Commented Mar 31, 2016 at 20:50
  • Also make sure you hit that readValue function in your controller. Commented Mar 31, 2016 at 20:50
  • Is it wordpress is_ajax() ? Commented Mar 31, 2016 at 20:51

2 Answers 2

1

I'll rewrite to my style

jQuery

<script type="text/javascript">
    $("#btn_refresh").click(function(){
        $.ajax({
            type:"POST",
            url: "SQLCommunication.php",
            dataType: "JSON",
            success : function(data){
                console.log(data);
                if(data.status === "success"){
                    alert("success");
                }else{
                    alert("error");
                }
            }
            error : function(XHR, status){
                 alert("fatal error");
            }
        })
    });
</script>

PHP

header('Content-Type: application/json');
function readValue(){
    $conn = establishConnection();
    if($conn->connect_error){
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT datetime, value FROM tempvalues";
    $result = $conn->query($sql);

    if($result->num_rows > 0){
        $row = $result->fetch_assoc();
        $arr["datetime"] = $row["datetime"]; //return datetime and value as array
        $arr["value"] = $row["value"];
        $arr["status"] = "success";
    }else{
        $arr["status"] = "error";
    }

    return json_encode($arr);
    $conn->close();
}

echo readValue();

Untested


Updated

functions.php

function readValue(){
    $conn = establishConnection();
    if($conn->connect_error){
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT datetime, value FROM tempvalues";
    $result = $conn->query($sql);

    if($result->num_rows > 0){
        $row = $result->fetch_assoc();
        $arr["datetime"] = $row["datetime"]; //return datetime and value as array
        $arr["value"] = $row["value"];
        $arr["status"] = "success";
    }else{
        $arr["status"] = "error";
    }

    return json_encode($arr);
    $conn->close();
}

function writeValue(){
     ...
}

SQLCommunication.php

header('Content-Type: application/json');
if(!isset($_GET['func']) && empty($_GET['func'])){
   //make the file inaccessible without $_GET
   $arr['status'] = "error";
   echo json_encode($arr);
   exit();
)

if($_GET['func'] === "readvalue"){
   echo readValue();
}elseif($_GET['func'] === "writevalue"){
   echo writeValue();
}elseif($_GET['func'] === "whatever"){
   //whatever...
}

  ....

jQuery

$("#btn_refresh").click(function(){
    $.ajax({
        type:"POST",
        url: "SQLCommunication.php?func=readvalue", //SQLCommunication.php?func=writevalue
        dataType: "JSON",
        success : function(data){
            console.log(data);
            if(data.status === "success"){
                alert("success");
            }else{
                alert("error");
            }
        }
        error : function(XHR, status){
             alert("fatal error");
        }
    })
});
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, that works. So i can't indicate which function of the .php - file i want to use? The ajax thing just gives me the echo of the php file. So basically, if i want to call more php functions i have to make a new file for every one?
@binaryBigInt That's a broad question, well, for me. For the code up there? You can save the functions like readValue() up there in functions.php, you name it. Access the functions.php through SQLCommunication.php. Then, use $_GET method on SQLCommunication.php. That's how to make it dynamic, at least what's on my mind right now. I can update my answer if you want it.
Yes, please give me a short example of what you mean. That would be very helpfull!
Thanks for your updated post but now i am getting an error: pastebin.com/01jXS1XG
@binaryBigInt What kind of error? Post on another question, please.
1

If you want to see the result in your ajax response, you have to use echo(), or any other printing method in your controller instead of return

2 Comments

What do you mean with "controller"?
Script or function if you prefer. Controllers are code file's name in MVC architecture (like Symfony or Laravel for PHP).

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.