Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
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

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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);
about 4 years ago · Santiago Trujillo Relatório

0

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;
    }
about 4 years ago · Santiago Trujillo Relatório

0

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.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda