Obtain JSON information and integrate it into an HTML document with the help of

I am currently working on a PHP/JSON file named users-json.php.

<?php
include_once('../functions.php');
if (!empty($_GET['id'])) {
$GetID = $_GET['id'];
$query = "SELECT Username, Firstname  WHERE UserID = :ID";
$stmt = $db->prepare($query);
$stmt->execute(array(':ID' => $GetID));
} else {
$query = "SELECT Username, Firstname FROM users";   
$stmt = $db->prepare($query);
$stmt->execute();
}
$userData = array();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){

      $userData[] = $row;
}
// Output user data as JSON
echo json_encode($userData);
?>

Here is the JSON output:

[{"Username":"Admin","Firstname":""},{"Username":"User","Firstname":"John"}]

I have a specific format in mind for displaying the data using jQuery.

+----+----------+-----------+----------+
| id | username | firstname | lastname |
+----+----------+-----------+----------+

Although I've attempted it myself, I haven't been successful so far.

Answer №1

To implement this functionality, you can utilize a combination of PHP and JavaScript.

Using JavaScript/JQuery:

Once you have retrieved your JSON data in the $userData variable within PHP, you will need to use $.parseJSON(); method from JQuery to parse the JSON into an object suitable for manipulation with JavaScript. Since the JSON is stored in a PHP variable initially, it needs to be converted into a JavaScript variable for further processing.

<?php
 $userdata = '[{"Username":"Admin","Firstname":""},{"Username":"Bruger","Firstname":"Ole"}]' 
?>

Your JavaScript code should resemble the following. Please make sure to include the JQuery library for proper functioning of the code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
  var data = '<?php echo $userdata ?>';
    var json = $.parseJSON(data);
        var html= "";

     for(i=0,no=1;i<Object.keys(json).length;i++){
     html+='<tr><td>'+json[i].Username+'</td><td>'+json[i].Firstname+'</td></tr>';
     }
    $('#data').html(html);
    </script>

You also need to structure your HTML as follows:

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<style type="text/css">
   table {
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
  }
  </style>
<body>
<table border="1">
<thead>
  <tr>
    <td>
    Username
    </td>
    <td>
    Firstname
    </td>
  </tr>
  </thead>
  <tbody id="data">  
  </tbody>
</table>
</body>
</html>

In Conclusion:

<?php
     $userdata = '[{"Username":"Admin","Firstname":""},{"Username":"Bruger","Firstname":"Ole"}]'
?>
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
<style type="text/css">
       table {
        border-collapse: collapse;
    }

    table, td, th {
        border: 1px solid black;
      }
      </style>
<table border>
  <tr>
    <td>
    Username
    </td>
    <td>
    Firstname
    </td>
  </tr>
  <tbody id="data">  
  </tbody>
</table>
</body>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
  var data = '<?php echo $userdata ?>';
    var json = $.parseJSON(data);
        var html= "";

     for(i=0,no=1;i<Object.keys(json).length;i++){
     html+='<tr><td>'+json[i].Username+'</td><td>'+json[i].Firstname+'</td></tr>';
     }
    $('#data').html(html);
    </script>
</html>

Answer №2

Thanks to your solution, everything is now working perfectly. I appreciate the detailed response which provided me with numerous insights.


    <script>
        $(document).ready(function() {
          $.getJSON("http://localhost/NewSite/php-pages/User-json.php", function(data) {
             var json = data;
             for(i=0,no=1;i<Object.keys(json).length;i++){
                 $('UserTable').append('<tr><td>'+json[i].Username+'</td><td>'+json[i].Firstname+'</td></tr>');
             }
         });
     });
    </script>

    <body>
    <table id="UserTable"></table>
    </body>

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

PHP requests that are asynchronous (without using AJAX)

Currently, I am working on developing an e-commerce application where I am utilizing a web service to create orders in an Oracle database. After sending the request, the webservice provides a response containing an OrderNumber which is then used to notify ...

What is the process for choosing with multiple attribute selectors?

Is there a way to disable multiple fields in a checkbox survey simultaneously? I attempted the following code, but it only works with one class. Is it possible to select by multiple classes within the same div? function surveyInit(){ $("div[class*=&apos ...

Convert your Node.js server URL hosted on AWS Elastic Beanstalk to HTTPS

Struggling to deploy my React JS app using AWS S3 bucket as I am new to the platform. The app communicates with a Node/Express server hosted on an Elastic Beanstalk environment. Encountered the error: Mixed Content: The page at 'https://myReactApp.s3. ...

Utilizing Express JS to Optimize JPEG File Loading with Cache Headers

I have been working on implementing Cache-Control for my static image files. I have successfully set this header for HTML and JS files: https://i.stack.imgur.com/9VuWl.png However, I am facing challenges with JPEG files: https://i.stack.imgur.com/p52jm. ...

Concerning the issue of components not loading correctly when using Angular with Lazy Loading Routing

Encountering an unusual issue while utilizing lazyload routing in our application! Within AppModule, there is TopModule followed by DashboardModule, all being loaded lazily. When localhost:4200/dashboard is accessed, the loading sequence is AppModule, To ...

PHP function that allows toggling only the first item in an accordion

In my function.php file in WordPress, I have the following code that is called using a shortcode on certain pages. It loops through and displays FAQs stored with each post. However, I am facing an issue where only the first accordion item can be toggled, ...

How to retrieve an unknown JSON key in Vue.js when using v-for loop?

I have developed a code analysis tool and I am looking to display my JSON data in a Vue table. The challenge is that I need the JSON key, which represents the package/file name of the directory whose data I want to showcase. Below is an excerpt of the JSO ...

Creating three functions with the same name, one with a callback, another with a promise, and the third with async/await, can

I am looking to create a versatile function that can be used in 3 different ways to handle npm dependencies Using Promises Using callbacks Using async/await For Instance 1) Using async/await var mongoose = require('mongoose'); async fu ...

Looking to display information in a column-by-column format using ng-grid within Angular JS

The data I have is structured like this: $scope.myStudentData = {"Moroni":{"id":"1","grade":"A"},"Tiancum":{"id":"2","grade":"B"}} However, the grid requires a different format: $scope.myGridOptions = [{"details":"id", "Moroni":"1", "Tiancum":"2"},{"det ...

The JSON response from XHR begins with the word "for."

While examining a few Facebook XHR requests, I noticed that there is a cross-domain request with a JSON response that begins like this: for (;;); {/* JSON object */} Why does the response start with a for? I suspect it might be for security reasons. Can ...

Mastering Data Labels in ng2-chart: A step-by-step guide

Once again, I find myself battling my Angular and JavaScript challenges, each question making me feel a little less intelligent. Let me walk you through how I got here. In my most recent project, I wanted to enhance the user experience by incorporating sl ...

Showing a cell border when a radio button is chosen

I am working with a table that contains input/radio buttons, and I am trying to figure out how to apply a border to a specific cell when the user selects the radio button within it. This will give the appearance of the cell being selected. I am not sure ho ...

The error "req.user is not defined" occurs when accessing it from an Android

I am currently collaborating with an Android developer to create an android app. While my colleague handles the front-end development, I focus on the backend work. Specifically, I have implemented the login and authentication features using node.js, expres ...

What are the best ways to combine, organize, and iterate through JavaScript objects?

When I run a loop, it returns a combination of integer values and objects as shown below: 2 {firstName:"John", lastName:"Doe", age:28, eyeColor:"blue"} 3 {firstName:"Jane", lastName:"Doe", age:22, eyeColor:"brown"} 1 {firstName:"Jack", lastName:"Doe", age ...

Building an AJAX form with error validation intact using simple_form

Seeking assistance from the experienced rails community, I present a challenging question that has left me stuck for days. In an effort to learn more about rendering, I am working on a dummy app based on this ajax/jquery tutorial. Following the guide, I s ...

Using JQuery and Javascript to retrieve information from one drop down list based on the selection made in another drop down

I'm currently working on a project that involves 2 drop-down menus. The first menu allows you to select a general model, while the second menu displays specific models based on your selection. http://jsfiddle.net/QskM9/ Here's an example of how ...

The PHP header location is failing to redirect and no HTTP status change is occurring

I'm encountering an issue with Headers in PHP. header('location: http:google.com'); is not functioning correctly. Here is my code snippet: if(!headers_sent()){ header("location: http://google.com"); exit; } HTML Data... The script ...

Retrieve data from each URL listed in a JSON array using React

My json file structure was as follows: [ { "name": "google", "route": "/google", "url": "www.google.com" }, { "name": "bing", "route": " ...

How can I transform this in JavaScript so that it returns a Promise?

Currently, I am trying to implement code that I found in a SaaS's example. The goal is to retrieve the correct URL for a specific action. The sample code provided by the SaaS looks like this, but I would like to modify it so that it returns a Promise ...

NodeJS: Implement a method to delete a file or folder using a path without the file extension (Strategic approach)

I am facing a challenge in deleting a file or folder based on a path that does not include an extension. Consider the path below: /home/tom/windows The name windows could refer to either a folder named windows OR a file named windows.txt Given that the ...