1

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

3
  • 1
    Where do you call the test function? Commented Apr 1, 2017 at 6:48
  • Also the function does not have return statement... at least for the JSON encode Commented Apr 1, 2017 at 6:50
  • The function does have a return statement Commented Apr 1, 2017 at 6:52

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

$con comes from another php file I will update my post
That doesn't matter. You can fix it with solution i provided. Your query is failing due to no connection found.
I can accept this answer in 5 minutes.However I cannot understand why isn't $con available inside my function
Function has its own scope for variables php.net/manual/en/language.variables.scope.php
1

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

Comments

1

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.

Comments

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.