1

I have a simple ajax call:

function init() {
    $.ajax({
        url: "./myFolder/user.php",
        data: {
            action: "init"
        },
        type: "post",
        success: function (output) {
            console.log("Success");
            console.log("Output: " + output);
        }
    });
}

The PHP init method gets called and simply should return some json data:

function init() {
    $arr = array(
        array(
            "region" => "valore",
            "price" => "valore2"
        ),
        array(
            "region" => "valore",
            "price" => "valore2"
        ),
        array(
            "region" => "valore",
            "price" => "valore2"
        )
    );

    return json_encode($arr);
}

but my console says:

Success
Output:

So the output variable is empty. Where is my json data?

4
  • Do you actually output the data given by init() somewhere, or do you just return it? Commented Jul 18, 2015 at 15:55
  • 1
    Are you sure the init() function is getting called? I mean, you know that writing action: "init" in the javascript doesn't call the php function, right? Echoing the encoded array should be enough. Commented Jul 18, 2015 at 15:58
  • echo json_encode($arr); Commented Jul 18, 2015 at 15:59
  • the solution of @Maxxi is correct. echo instead of return. but why? Commented Jul 18, 2015 at 16:05

2 Answers 2

1

On user.php page you need to do :-

function init() {
        $arr = array(
            array(
                "region" => "valore",
                "price" => "valore2"
            ),
            array(
                "region" => "valore",
                "price" => "valore2"
            ),
            array(
                "region" => "valore",
                "price" => "valore2"
            )
        );

        echo  json_encode($arr);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

why should i need that? i call my init method asynchronosly using javascript. so why should i call it in my php file? that makes no sense.
yes. now it is working. can you explain why echo is working and return isnt?
proper definition is given in this link:- stackoverflow.com/questions/10107144/…
-2

u should have in your user.php somthing like this:

die(init());

2 Comments

sorry... but... what?
What exactly don't you understand? your php script should not just generate data but OUTPUT it. with echo, die, etc

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.