I have a javascript file in which I am doing an ajax request to foo.php
in order to get an array of mysql results.
Here is my javascript file.
//foo.js
$(document).ready(function(){
    $.ajax({
        url:"foo.php",
        type:"POST",
        data:{
            action:"test",
            remail:"foo"
        },
        success:function(data){
            var messages = data;
            console.log("Ext req");
            try{
                console.log(JSON.parse(data));
            }catch(e){
                console.log(data);
            }
        },
        failure:function(){
        }
    })
});
In order to receive my array of results from php I do the following:
//foo.php
<?php 
    if(isset($_POST)){
        $action = $_POST['action'];
        if(empty($action)){
            return;
        }
        switch($action){
            case "test":
                $query = "select * from message where seen";
                $ar = [];
                $res = mysqli_query($con,$query);
                while($row = mysqli_fetch_array($res)){
                    $ar[] = $row;
                }
               echo json_encode($ar);
            break;
        }
    }            
?>
This returns an array of objects to my ajax request which then I can handle according to my needs. However if I try to move the php code inside the switch statement into a function and return the encoded result of the function I only get an empty array as response. Here is how I am trying to do it:
<?php 
    function test(){
        $query = "select * from message where seen";
        $ar = [];
        $res = mysqli_query($con,$query);
        while($row = mysqli_fetch_array($res)){
            $ar[] = $row;
        }
        return $ar;
    }
    if(isset($_POST)){
        $action = $_POST['action'];
        if(empty($action)){
            return;
        }
        switch($action){
            case "test":
                $result = test();
               echo json_encode($result);
            break;
        }
    }            
?>
Any ideas why this happening?
UPDATE
$con is a variable that comes from another file which I include