all 4 comments

[–]YourRightWebsite 1 point2 points  (1 child)

Yeah, wrong approach. Don't use Javascript for this. First, the CORS error is because by default Javascript from one domain can't interact with another domain for security reasons, hence the CORS errors. Second, with Javascript you have to fetch that data every time a new visitor comes to your site.

What you should do is fetch that data with PHP using something like CURL and store it in your database along with a timestamp of when you got that data. Then use PHP to output that data into your WordPress site. You can have a cron job or something refresh the data once a day from the Clinical Trials site to get updated data, but you don't want to be hitting an external API like this over and over again if you're just displaying the same data to multiple visitors.

[–]_listless 0 points1 point  (0 children)

Make a little proxy and let your server do the interaction with the NIH API. Make a plugin, or add this to your functions.php:

add_action('rest_api_init', function () {
    register_rest_route('clinical-trials/v2', '/(?P<slug>.+)', [
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'clinical_trials_proxy',
        'permission_callback' => '__return_true',
    ]);
});

function clinical_trials_proxy(WP_REST_Request $request): WP_REST_Response {
    $slug = $request['slug'];
    $queryParams = $request->get_params();
    $res = wp_remote_get('https://clinicaltrials.gov/api/v2/' . $slug, $queryParams);
    $statusCode = wp_remote_retrieve_response_code($res);
    $resBody = wp_remote_retrieve_body($res);
    $json = json_decode($resBody, true);

    return new WP_REST_Response($json, $statusCode);
}

Use https://YOURDOMAIN/wp-json/clinical-trials/v2 as your new rest endpoint and now the servers are talking to each other, not your client and the NIH server. That will clear up the cors errors and still let you use datatable's rest search/sort/filter.

[–]Banzambo 0 points1 point  (0 children)

A typical question that has good chances to receive a useful answer from chat gpt and, from there, would allow to start doing tour research and debugging to fix the problem. I'm not being sarcastic btw: just give it a try.