Load HTML table values dynamically with Ajax post page load in PHP

My goal is to retrieve the connectivity status of available servers in a database on a PHP page.


<tbody>
<?php foreach ($data['servers'] as $server) { ?>
     <tr>
          <td class=""><?php echo $server->server_name; ?></td>
          <td class=""><?php echo $server->base_path; ?></td>
          <td class="server_status"><?php if (is_dir($server->base_path)){ echo 'Pass';} else { echo 'Fail' } ?></td>
    </tr>
  <?php  } ?>
  </tbody>

I aim to achieve this right after the page loads using AJAX, similar to this page screenshot

How can I invoke AJAX to obtain each value from this dynamically generated table? I have attempted the following code so far:

<?php foreach ($data['servers'] as $server) { ?>
     <tr>
          <td class=""><?php echo $server->server_name; ?></td>
          <td class=""><?php echo $server->base_path; ?></td>
          <td class="server_status"></td>
          <td class="server_status_loading"></td>
    </tr>
  <?php  } ?>

JS

$(function(){

$(".server_status").hide();
$(".server_status_loading").show();
$.ajax({
    url: 'get-server-status'
})
.error(function(){
    alert('Error!');
})
.done(function(response){

    $(".server_status_loading").hide();
    $(".server_status").show();
    $(".server_status").html(response);
});

Function for get-server-status:

public function getStatus() {

    $basePath = $this->_serverModel->getBasePath(2);
    if (is_dir($basePath)) { 
        echo 'Pass'; exit;
    } 
    else { 
        echo 'Fail'; exit;
    }
}

Thank you in advance!

Answer №1

Begin by adding an id attribute to your <tr>.

<?php foreach ($data['servers'] as $server) { ?>
 <tr id="echo database id here.">
      <td class=""><?php echo $server->server_name; ?></td>
      <td class=""><?php echo $server->base_path; ?></td>
      <td class="server_status"></td>
      <td class="server_status_loading"></td>
</tr>

Next, refer to this link here to handle the ajax on page load and click on this link for ajax handling on click. All necessary information is provided in those links.

In the links provided, you can substitute status with server_status_loading

Answer №2

Give this a try

$(document).ready(function(){
    var table = document.getElementById('table2');
        var rowCount = table.rows.length;

    for(var j=1; j<rowCount; j++){
        path = table.rows[j].cells[2].childNodes[1].value;      
        $.ajax({
           url: 'check-server-status',
           data :path 
        })
    .error(function(){
        alert('There was an error!');
    })
    .done(function(result){
        table.rows[j].cells[2].childNodes[3].value=result;
    });

    }
}

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

Leverage Pinia store in Vue helper functions

I have been working on my Vue.js application and I am looking to implement some helper functions that will utilize a Pinia store within the app. These functions need to be accessible by multiple components. Should I define these helper functions directly ...

Can an input element be used to showcase a chosen image on the screen?

I would like to display the selected image from an input element. Can this be done with a local file, accessing the image on the client side, or do I need to upload it to a server? Here is my React code attempt: I can retrieve the correct file name from t ...

Managing User Session Timeout in Ruby on Rails with Devise

My application is utilizing devise for security, with a session timeout set to 30 minutes. Everything works fine when users navigate normally - if they click a link after timing out, they are redirected to the login screen with a message stating "Your sess ...

Issue with file upload in jQuery form plugin leads to Uncaught TypeError

When I don't select a file for upload and only fill in the other inputs before posting the form, everything works fine. However, if I choose a file for image upload and then try to post it, I receive an error message. Interestingly, when I check the f ...

Display information from a Google Sheet onto a leaflet map based on specified categories

I am currently facing some challenges while creating a map with markers using data from Google Sheet and leaflet. Despite my efforts, I have encountered a few bugs that are proving to be difficult to resolve: Group Filtering - Although I can successfully ...

Guide to identifying a particular keyword within a vast database of text

I've been grappling with this problem for a day now, focusing on the PHP + MYSQL aspect. However, due to the large amount of data, most of the scripts I've attempted have timed out. Our database consists of two tables: People with approximatel ...

Set attributes to the main ul elements

My knowledge of jquery is still developing, and I have encountered what seems to be a fairly straightforward issue. I am in the process of setting up a flyout menu for navigation on a new website. However, due to restrictions imposed by my CMS, I am unabl ...

Can you add a new letter right after the initial character of a string

$variable = "Hi"; I need assistance with adding the character : directly after the first character in the given string. The initial character can vary, so I would like to achieve something similar to this: $result = addToString("Hi"); echo $result; // sh ...

Resource loading error: The server returned a 404 (Not Found) status code, as shown in the console

Click here I have a simple file structure where index.html, script.js, and login.js are all in the same root folder without any subfolders. The issue I'm facing is that although the connection to the database works fine, there seems to be a problem wi ...

Is there a way to ensure that a "catch all other" route in the Vue Router will also capture the URL if a portion of it matches a predefined route?

After following the suggestion to implement a catch all route from this article, I realized that it does not capture URLs that partially match a defined route. routes: [ { path: "/album/:album", name: "album", component: Album, } ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...

How can I best fill the HTML using React?

After attempting to follow various React tutorials, I utilized an API to fetch my data. Unfortunately, the method I used doesn't seem to be very efficient and the code examples I found didn't work for me. I am feeling quite lost on how to proper ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

Adding events to a TinyMCE iframe in WordPress

Recently, I implemented some customized div wrapper styles in Wordpress. However, when utilizing these styles on a page, I encountered difficulties adding content below them. Despite using CSS:after within the divs to generate a selectable area, this metho ...

ng-grid defines different cellClass based on the value of the field

I am currently using the ng-grid and I want the column to display in a different color based on different values. I have tried, but not succeeded so far... $scope.gridOptions = { ........ columnDefs: [ { field: "status", displayName: "St ...

"Learn the process of extracting information from a database and exporting it to a CSV file with Angular 2

Currently, I am facing an issue where I need to retrieve data from a database and export it to a CSV file. While I am able to fetch all the data successfully, I am encountering difficulty when trying to fetch data that is in object format as it shows up as ...

AngularJS Pagination: Organizing Content Efficiently

Utilizing Bootstrap's Pagination directive to implement pagination in a table. Interestingly, when manually adding data to $scope.transactions (referencing the commented out code in the controller), the pagination functions flawlessly. However, attem ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

Converting numbers from the format of (-/+)xx.xxxxxxxxx to xxxx.xxxx using PHP

Can anyone help me with formatting a number as xxxx.xxxx? The input format I have is (-/+)xx.xxxxxxxxx. If the number is in the format x.xx, it should be converted to the desired format by adding zeros at both ends. I would appreciate guidance on the cor ...

How can I retrieve the Azure subscription IDs of the currently logged in user using @azure/msal-angular?

I successfully authenticated a user using @azure/msal-angular and received the id_Token, access_Token and tenant Id. Now I am looking to retrieve the logged in user's azure subscriptions. Is there a way to achieve this through msal or are there any Ja ...