user1170330 user1170330 - 2 months ago 8
Ajax Question

Displaying Results from Prepared Statements

I have the following table:

| id | name | age |
|----|-------|-----|
| 1 | Peter | 23 |
| 2 | Amie | 34 |
| 3 | Eddy | 45 |
| 4 | Peter | 56 |
| 5 | Eddy | 67 |


I now want to retrieve the age of all users with the name
Peter
.

JS:

function getAge() {
$.ajax({
type : "POST",
url : "backend.php",
data : {
q : "user",
name : 'Peter'
},
success : function(data) {
console.log(data)
if (data.length > 0) {

} else {
console.log("empty")
}
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}


PHP:

if (isset ( $_POST )) {
if ($_POST ['q'] == "user") {
$name = $_POST ["name"];

$stmt = $link->prepare ( "SELECT age FROM tab1 WHERE name= ?" );

$stmt->bind_param ( "s", $name );
$stmt->execute ();
$stmt->store_result ();

if ($stmt->num_rows >= 1) {
echo "Yes"; // only this Yes is being returned
$arr = array ();
while ( $stmt->fetch () ) {
$arr [] = $name;
}
return $arr;
} else {
echo "0 records found";
}

$link->close ();
}


Instead of an array with
23
and
56
, I only get a
Yes
.

So how can I get the array with the ages?

Answer

just add this into your php function. this means you want to return json into this page

header('Content-Type: application/json');

change your return $arr to echo json_encode($arr); to convert your array into a json object also remove your echo "Yes";

echo json_encode($arr);

your php function will look like this

if (isset ( $_POST )) {
   if ($_POST ['q'] == "user") {
        header('Content-Type: application/json');
        $name = $_POST ["name"];

        $stmt = $link->prepare ( "SELECT age FROM tab1 WHERE name= ?" );

        $stmt->bind_param ( "s", $name );
        $stmt->execute ();
        $stmt->store_result ();

        if ($stmt->num_rows >= 1) {
            $arr = array ();
            while ( $stmt->fetch () ) {
                $arr [] = $name;
            }
            echo json_encode($arr);
        } else {
            echo "0 records found";
        }

        $link->close ();
    }
}
Comments