What could be causing my custom WordPress route to not retrieve data from the database properly?

Within the following code snippet lies a custom endpoint that aims to extract data from the saic3_LibraryIndex database.

<?php
add_action('rest_api_init', function () {

    register_rest_route('libraries/v1', '/all', array(
        'methods' => 'GET',
        'callback' => 'retrieve_libraries'
    ) );

} );

function retrieve_libraries( $data ) {

    global $saic3_LibraryIndex;
    $query = "SELECT * FROM `Library`";
    $list = $saic3_LibraryIndex->get_results($query);
    return $list;

}

In my JavaScript, I trigger an ajax call on page load to dynamically populate the page with data from the database. Currently, I'm using this call to confirm if I am receiving any data.

<script type="text/javascript"> 


jQuery(document).ready(function( $ ){

    $.ajax({
        url: "/wp-json/libraries/v1",
        method: 'GET',
        success: function(response) {
            console.log(response);
        },
        failure: function(err) {
            console.log(err);
        }
    });
});

</script>

The route is successful in hitting and not resulting in a 404 error, but the response I receive back is empty. The response looks like this:

{namespace: "libraries/v1", routes: {…}, _links: {…}}
     namespace
     :
     "libraries/v1"
     routes
     :
     /libraries/v1
     :
     endpoints
     :
     [{…}]
     methods
     :
     ["GET"]
 namespace
 :
 "libraries/v1"
 _links
 :
 {self: "{`my-url-.com`/wp-json/libraries/v1"}
 __proto__
 :
 Object
 /libraries/v1/all
 :
 endpoints
 :
 [{…}]
 methods
 :
 ["GET"]
 namespace
 :
 "libraries/v1"
 _links
 :
 {self: "`my-url-.com`/wp-json/libraries/v1/all"}
 __proto__
 :
 Object
 __proto__
 :
 Object
 _links
 :
 up
 :
 [{…}]
 __proto__
 :
 Object
 __proto__
 :
 Object

Being new to WordPress, any guidance on this matter would be highly appreciated. I was informed that the database is named saic3_LibraryIndex, which I assumed would replace wpdb. I also attempted switching it to wpdb and fetching local posts, but the console still displays the same response. I strongly believe that the endpoint is incorrectly written, but I lack the knowledge to correct it.

Answer №1

RESOLVED

In order to connect to a separate database from wpdb, I had to instantiate a new wpdb object as shown below:

add_action('rest_api_init', function () {
    register_rest_route('libraries/v1', '/all', array(
    'methods' => 'GET',
    'callback' => 'retrieve_libraries'
    ) );
} );

function retrieve_libraries( $data ) {
    $second_db = new wpdb(DB_USER, DB_PASSWORD, "saic3_LibraryIndex", DB_HOST);
    $query = "SELECT * FROM `Library`";
    $list = $second_db->get_results($query);
    return $list;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining attribute from an object using JQuery

I am experiencing an issue with extracting the innerHTML from an object. The code I currently have is as follows: console.log( $(myString).find("#" + someID).prevObject ); The variable myString contains HTML code in string format someID represents the ...

What alternative can be used for jquery isotope when JavaScript is not enabled?

Is there a backup plan for jQuery isotope if JavaScript isn't working? For instance, if I'm using the fitColumns feature, is there an alternative layout style available in case JavaScript is disabled, similar to what is seen on the new Myspace? ...

Unpredictable Behavior of CSS Transition with JS createElement() Function

I'm using JavaScript to create a div element and I'm adding the CSS property transition: .5s linear top; When the user clicks on the element (onmousedown event), it is supposed to smoothly move to the top of the screen and then be deleted using ...

The variable within my function is not being cleared properly despite using a jQuery function

Recently, I encountered an issue with a function that displays a dialog box to ask users if their checks printed correctly. Upon clicking on another check to print, the "checked_id" value remains the same as the previously executed id. Surprisingly, this i ...

The preg_split function stored all results in an array

Having an issue with the preg_split function in PHP. My regular expression is: #^(-?[0-9]+)(([+x])(-?[0-9]+))*$# I am trying to transform this input: -5+69x45 into an array like this: { [0] = -5 [1] = + [2] = 69 [3] = x [4] = 45 } The regular expres ...

The variable is constantly reverting back to its initial value

Here is the code snippet: function send() { var nop = 6; var send_this = { nop: nop }; $.ajax({ type: "GET", data: send_this, url: "example.com", success: function(r) { ...

How to Exclude Objects in Laravel Blade Template

One inquiry that I have is about the best practice when using Laravel. I have a blade page that displays all of my products, and in my loop, I check if the product has an image. If it does, then I ignore it: @foreach ($products as $product) @if(is_nul ...

Modifying the DateTime in doctrine proves to be a challenge

Seeking assistance on how to update the DateTime using Doctrine in my controller. The main objective of this page is to enable users to upload photos to a database, with only one upload allowed per user. Although everything else is functioning properly, ...

Calculate the straight line path between points A and B using latitude and longitude coordinates. Determine if a given point is within a certain distance from

After struggling with this problem for a couple of days, I still haven't found a solution :( There is a route on the map from point A to point B in a straight line. Both points have latitude and longitude coordinates. My goal is to determine if point ...

Checkbox form for updating entries in the SQL database table

My goal is to make changes to a MySQL table using an HTML form. Here's a snippet of the form: <div id="caricoModal" class="modal fade"> <div class="modal-dialog"> <form method="post" ...

Guide on making a prev/next | first/last button functional in list.js pagination

Is there a way to enhance my paginated index by adding prev/next, first/last buttons? I am curious if anyone has implemented these features using List.js. <script src='//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js&ap ...

Issue with margins of sections when attempting to activate menu class while scrolling

My Objective: I want to create a website where the menu highlights the section that is currently being viewed as the user scrolls up and down. Progress So Far: I have successfully implemented a functioning menu that changes to "active" when the correspo ...

Creating a customized JSON object with Laravel framework

Hey Team, I'm facing an issue with structuring my JSON output correctly. What I have in mind is the desired output below: { comments: { data: { created_at: "date", other: "etc", from: { username: ...

Error encountered when using the $.post function

$(".eventer button[name=unique]").click(function() { console.log('button clicked'); thisBtn = $(this); parent = $(this).parent(); num = parent.data('num'); id = parent.data('id'); if(typeof num ! ...

What steps can I take to ensure that my keyup function is not delayed by one character?

Whenever I type something in my textarea, I want the text to instantly display in my result box. I've tried using both the keyup and keydown functions, but I'm facing an issue where there is a delay of one character when typing quickly. For exa ...

Is there an alternative method for locating the http referrer?

I currently have a virtual Linux server running Apache2 and PHP, with Tor serving as a hidden service. I am trying to retrieve the HTTP REFERRER information but have found that $_SERVER['HTTP_REFERER'] is not reliable and should not be used. Afte ...

Can cookies operate on a local server?

Similar Question: Cookies on localhost with explicit domain Here is the code snippet that I am using after the user has logged in: setcookie("user",$entered_username, time()+(60*60*5)); setcookie("password",$entered_password, time()+(60*60*5)); ...

The Jquery .clone() function presents issues in Internet Explorer and Chrome browsers, failing to perform as expected

I need to duplicate an HTML control and then add it to another control. Here is the code I have written: ko.bindingHandlers.multiFileUpload = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { va ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

Calculating the total amount by combining the quantity and price fields in

I currently have multiple tables generated dynamically using PHP <table class="table11"> <tbody> <tr> <td>Name</td> <td class="quantity">2</td> <td class="price">20</td> & ...