使用ajax从文件中获取编码数组

I was trying to grab an encoded array [{"got":"1235.00","needed":"4350"}] from a file using this code:

function getNewValues(){
        $.ajax({
            dataType: 'json',
            url: 'get.php',
            type: 'POST',
            cache: false
        })
        .success(function(data) {
            return data;
        })
        .fail(function() {
            console.log("An error ocurred");
        })
    }

But the problem is that the only thing i get back in the return data is array( object ), the problem is that i dont know whats wrong or in wich file it went wrong.

generating the encoded array:

<?php
  $pdo = new PDO('mysql:host=127.0.0.1;dbname=thermometer', 'root', ''); 
  $sql = 'SELECT `got`.`value` AS got, `needed`.`value` AS needed FROM `needed`, `got`'; 
  $statement = $pdo->prepare($sql);
  $statement->execute();
  $result = $statement->fetchAll(PDO::FETCH_ASSOC);
  $json = json_encode($result);
  print_r($json);
?>

It would be nice if someone has an solution for this becouse i cant solve it :(

Your issue is that the function has finished by the time the data arrives. This is due to the asynchronous nature of AJAX. You need to handle your data when it arrives, not assume it has arrived before it has.

function getNewValues(){
    $.ajax({
        dataType: 'json',
        url: 'get.php',
        type: 'POST',
        cache: false
    })
    .success(function(data) {
        // Handle your data here;
    })
    .fail(function() {
        console.log("An error ocurred");
    });

 // Attempting to use the data or returning the data here will not work!
}

Edit: Reread your question. Think this response to a similar question could help.

Once you have executed the prepared statement, something like this could work instead of the PDO::FETCH_ASSOC

...
$result = $statement->execute();
for ($file_data = array(); $row = $result->fetch_assoc(); $file_data[] = $row);

$file_data is then an associative array of whatever data it is you want.

print json_encode($file_data);

You need to set and return the variable inside the function, not try to return the ajax return value as the function. In other words, pass the ajax return to a variable to a function variable and then return that. Something like this:

function getNewValues(){
   var returnedJSON= $.ajax({
        dataType: 'json',
        url: 'get.php',
        type: 'POST',
        cache: false
    })
    .success(function(data) {
        return data;
    })
    .fail(function() {
        console.log("An error ocurred");
    })
   return returnedJSON;
    }