Call PHP function with JavaScript Ajax to get database values

Posted by

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.try print_r(json_encode($arr)).

You need to invoke the readValue() function in your PHP code and echo its result And you don’t need to call parseJSON as I know. Also make sure you hit that readValue function in your controller.

Answer 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();

call php function from javascript with ajax

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");
        }
    })
});

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?

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. – Chay22

javascript call php function with parameters

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.

Script or function if you prefer. Controllers are code file’s name in MVC architecture (like Symfony or Laravel for PHP).

More Post Like This :- PHP Display Errors PHP AJAX pagination

The post Call PHP function with JavaScript Ajax to get database values appeared first on PHP Question Answer.

Leave a Reply

Your email address will not be published. Required fields are marked *