Ajax response is null on PHP correctly handled data

时间:2018-07-05 12:14:09

标签: php jquery ajax

I have a form that performs a POST call on a php file on the server; the request is processed correctly, but when I try to handle it, it is shown as a null value. Here my php fragment:

<?php
header('Access-Control-Allow-Origin: *');

require_once 'access.php';

//connection to db
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if (mysqli_connect_errno()) { //verify connection
    echo "Error to connect to DBMS: ".mysqli_connect_error(); //notify error
    exit(); //do nothing else
}

//Take user team request
$teamchoice = $_POST['team'];

//retrieving all people of that team
$query = "SELECT * FROM pokecods WHERE team = '$teamchoice'";
$result = $mysqli->query($query);


if ($result->num_rows > 0) 
    echo json_encode($result);
else
    echo 'Oops, something went wrong';

$result->close();
$mysqli->close();
?>

The query performs correctly, because as result I have a json object (there's only one object that matches the query in the db), but when I try to handle this object, I have this result: result

提交表单

这是我的jQuery代码:

    $.post(post_url, post_data)
        .done( function(response) {
var json = JSON.parse(response);        
    console.log(json);
})
        .fail( function() {
            alert("The AJAX request failed!");
        });

为了正确处理我的对象,我该怎么办?

1 个答案:

答案 0 :(得分:0)

您在执行查询后忘记了获取结果。使用fetch_all获取结果,然后传递给json_encode

更新的代码:

if ($result->num_rows > 0) {
    $records = $result->fetch_all(MYSQLI_ASSOC);
    echo json_encode($records);
} else {
    echo 'Oops, something went wrong';
}