ajax – Removes the button if the answer returns no element

PHP / HTML:

    <a id = "load-more" data-per = ""> load more

    JavaScripts:

    (function ($) {
    // Get the Load more button, because I only want to execute the code if the button is on the page.
    var loadMoreButton = $ ("# load-more");
    
    if (loadMoreButton) {
    // Get the posts_per_page number set in the read options
    var per = loadMoreButton.data ("per");
    
    // Initialization function
    var loadPosts = function (page) {
    var theData, loadMoreContainer, errorStatus, errorMessage;
    
    // The AJAX request
    $ .ajax ({
    url: "https://ruizhang.org/wp-json/wp/v2/posts",
    dataType: "json",
    The data: {
    // Matches the query already executed on the page
    per_page: per,
    page: page,
    type: "post",
    orderby: "date"
    }
    success: function (data) {
    // Removes the button if the response does not return any items
    if (data.length <1) {
    loadMoreButton.remove ();
    }
    
    // Create a place to store exactly what I need
    // Otherwise, the response can be filtered to return only the necessary data, which is probably more efficient because the next loop will not be necessary.
    theData = [];
    
    // only get what I need and store it
    for (i = 0; i <data length; i ++) {
    the data[i] = {};
    the data[i].id = data[i].id;
    the data[i].link = data[i].link;
    the data[i].title = data[i].title.rendered;
    the data[i].content = data[i].content.rendered;
    }
    
    // Take the container where my data will be inserted
    loadMoreContainer = $ ("# load-more-div");
    
    // For each object in my newly formed array, create a new element to store that data and insert it into the DOM.
    $ .each (theData, function (i) {
    loadMoreContainer.append (
    & # 39;
  • & # 39; + the data[i].title + "
  • " ) }); } error: function (jqXHR, textStatus, errorThrown) { errorStatus = jqXHR.status + "" + jqXHR.statusText + " n"; errorMessage = jqXHR.responseJSON.message; // Show me what was wrong console.log (errorStatus + errorMessage); } }); }; // As our AJAX request is identical to the original request of the page (page 1), start with page 2 var getPage = 2; // Really implements the feature when the user clicks the button loadMoreButton.on ("click", function () { loadPosts (getPage); // Increment the page, so at the next click we get the next page of results getPage ++; }); } }) (jQuery);

    That's the problem, it does not remove the link.

    // Removes the button if the response does not return any items
    if (data.length <1) {
    loadMoreButton.remove ();
    }
    

    Console errors by clicking after reaching the end of messages:

    400 bad demand

    The requested page number is greater than the number of available pages.