简体   繁体   中英

Can't return array from php function to ajax request

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

When you moved your query logic into a function, $con , MySQL's connection object is not available. Use GLOBAL $con; inside your function.

Read this to understand Variable Scope

Method 1 Using GLOBAL keyword

function test(){
    GLOBAL $con;

    $query = "select * from message where seen";
    $ar = [];
    $res = mysqli_query($con,$query);
    while($row = mysqli_fetch_array($res)){
        $ar[] = $row;
    }
    return $ar;
}

Method 2 Pass an argument to a function

function test($con){
    $query = "select * from message where seen";
    $ar = [];
    $res = mysqli_query($con,$query);
    while($row = mysqli_fetch_array($res)){
        $ar[] = $row;
    }
    return $ar;
}

Call it like this:

test($con);

Global variables if not used carefully can make problems harder to find as other solution suggested. Pass $con as argument to your function:

function test($con){
        $query = "select * from message where seen";
        $ar = [];
        $res = mysqli_query($con,$query);
        while($row = mysqli_fetch_array($res)){
            $ar[] = $row;
        }
        return $ar;
    }

Let us talk about the problems you have:

  1. You pass a failure function to $.ajax . You surely wanted to use error instead of failure . See here .

  2. You have a messages variable initialized, but unused inside success . Get rid of it.

  3. You check for isset($_POST) , but that will always be true . You wanted to check isset($_POST["action"]) instead, or you wanted to check whether it is a POST request .

  4. $con is not available inside the function . You will need to either initialize it inside the function or pass it to it and use it as a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM