-3

I'm trying to get PHP returned array from Ajax.

Here is my Ajax call:

enter image description here

And my PHP code is this:

enter image description here

Query is running perfectly.

enter image description here

I have tried to get values like alert(data[0].program_title) in ajax success. But it also returns Undefined.

How can I fix this issue?

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388

3 Answers3

2

In your PHP code:

//remove
return $data

//change with
echo json_encode($data);
Stefano Pascazi
  • 341
  • 1
  • 10
1

Just before flushing the data back to the stream (returning), convert your data ($data variable in this case) to JSON string using json_encode and add the proper content-type application/json using header function.

However, the best practice is to provide some metadata to your data included in your transfer, like the size of data and count of elements in data and if paginated, which page the data refers to and what the maximum available pages and maximum element size of a page are.

Here's a sample body structure for a more robust data transfer:

$response = [
   'page'          => 0,   // e.g.
   'count'         => count($data),
   'data'          => $data,
   'max_page'      => 3,   // e.g.
   'item_per_page' => 15,  // e.g.
   'status_code'   => 200, // e.g.
];
header ( "Content-Type: application\/json", true , 200);
return json_encode(
   $response
   , JSON_INVALID_UTF8_SUBSTITUTE
      | JSON_NUMERIC_CHECK
      | JSON_PRESERVE_ZERO_FRACTION
      | JSON_UNESCAPED_LINE_TERMINATORS
      | JSON_UNESCAPED_SLASHES
      | JSON_UNESCAPED_UNICODE
);
Cunning
  • 799
  • 8
  • 27
0

Try this:

$data = [];
if ($numRows>0) {
    while($row=$result->fetch_assoc()) {
        $data[] = $row;
    }
}

Replace return with echo and add json_encode

echo json_encode($data);
failedCoder
  • 1,235
  • 1
  • 7
  • 28