October 21, 2024
Chicago 12, Melborne City, USA
PHP

How do I return the response from an asynchronous call?


My goal is to fetch data from MySQL using PHP and Vanilla JS and populate an HTML table using list.js. Fetch is successfully retrieving the data in JSON format; however, I am not 100% sure it’s correct, but I am trying to mimic the example given.

Here is the basic outline of the JS:

function listCalendarEvents() {
    
    fetch('/google/listCalendarEvents/') // Replace with your API endpoint
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json(); // Assuming the response is JSON
      })
      .then(data => {
        // Handle the fetched data
        console.log(data.events);
        return data.events;
      })
      .catch(error => {
        // Handle errors
        console.error('There was a problem with the fetch operation:', error);
      });
}
const orders = listCalendarEvents();

which then sets the var "order" in window.List();

const orderList = new window.List(table, options, orders);

When the script is fired off, it retrieves the data from a PHP controller that outputs the JSON formatted data that I need like such:

public function listCalendarEvents()
{
    $events = $this->google_m->listCalendarEvents();
    echo json_encode(array('response' => 1, 'events' => $events));
    
    exit();
}

Once that data is retrieved, the HTML table displays undefined in each column. I made sure all variables and fields were correct. When using the static example of data below, it works… again, I’m not sure if the data is being formatted correctly.

Here is the console output:

(2) [{…}, {…}]
0
: 
dateTime
: 
"2024-10-24T07:00:00-07:00"
description
: 
null
endDate
: 
null
hangoutLink
: 
null
startDate
: 
null
summary
: 
"Meeting with Johnny Bravo"
[[Prototype]]
: 
Object
1
: 
{summary: 'November test for the GCAPI', description: null, startDate: null, endDate: null, dateTime: '2024-11-07T06:00:00-08:00', …}
length
: 
2
[[Prototype]]
: 
Array(0)

Any help would be great! Thank you!

Sample data which works:

const orders = [
  {
    id: 1,
    summary: 'order-dropdown-1',
    description: '#2181',
    hangoutLink: 'mailto:carry@example.com'
  },
  {
    id: 2,
    summary: 'mailto:milind@example.com',
    description: 'Milind Mikuja',
    hangoutLink: '10/03/2023'
  },
  {
    id: 3,
    summary: 'order-dropdown-3',
    description: '#2183',
    hangoutLink: 'mailto:stanly@example.com'
  }
];



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video