Why is it difficult to display data fetched through getJSON?

The test-json.php script retrieves data from the database and converts it into JSON format.

<?php
$conn = new mysqli("localhost", "root", "xxxx", "guestbook"); 
$result=$conn->query("select * From lyb limit 2"); 
echo '[';
$i=0;
while($row=$result->fetch_assoc()){  ?>
 {title:"<?= $row['title'] ?>",
        content:"<?= $row['content'] ?>",
        author:"<?= $row['author'] ?>",
        email:"<?= $row['email'] ?>",
        ip:"<?= $row['ip'] ?>"}
<?php 
if(
$result->num_rows!=++$i) echo ',';   
}
echo ']'    
?>

When running select * From lib limit 2 on my database, it fetches the following records:

title    | content   | author   | email            |ip
welcome1 | welcome1  | welcome1 | <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087f6d646b67656d39487c6765266b687964686c">[email protected]</a> |59.51.24.37
welcome2 | welcome2  | welcome2 | <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6611030a05090b03542612090b4805090b00070b09064e030f0d">[email protected]</a> |59.51.24.38

To execute the script, use

php -f /var/www/html/test-json.php
.

[ {title:"welcome1",
         content:"welcome1",
        author:"welcome1",
         email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f186949d929e9c94c0b1859e9cdf8295979a">[email protected]</a>",
        ip:"59.51.24.37"},
{title:"welcome2",
         content:"welcome2",
        author:"welcome2",
         email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1d6c4cdc2ceccc493e1d5cecc91cec3cf">[email protected]</a>",
        ip:"59.51.24.38"}]

The retrieved data in JSON format can be displayed in a table by using JavaScript for calling back.

Below is the HTML code to show the AJAX response in a table:

<script src="http://127.0.0.1/jquery-3.3.1.min.js"></script>
<h2 align="center">Ajax show data in table</h2>
<table>
    <tbody id="disp">
        <th>title</th>
        <th>content</th>
        <th>author</th>
        <th>email</th>
        <th>ip</th>
    </tbody>
</table>

<script> 
$(function(){
    $.getJSON("test-json.php", function(data) {
        $.each(data,function(i,item){
            var tr = "<tr><td>" + item.title + "</td>"    +
                        "<td>"  + item.content  + "</td>" +
                        "<td>"  + item.author  + "</td>"  +
                        "<td>"  + item.email  + "</td>"   +
                        "<td>"  + item.ip  + "</td></tr>"
            $("#disp").append(tr);
        });
    });
});
</script>

After typing 127.0.0.1/test-json.html, you may notice no data being generated on the webpage despite executing test-json.php.

Expected output should look like this in the table:

Ajax show data in table
title   content author  email   ip
welcome1  welcome1  welcome1  <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1067757c737f7d752150647f7d3e777b797d">[email protected]</a>  59.51.24.37
welcome2  welcome2  welcome2  <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0a7b5bcb3bfbdb5e290a4bfbdbe97bab6b4">[email protected]</a>  59.51.24.38

Answer №1

It seems like the issue lies in the response generated by your PHP script, which is not valid JSON.

JSON requires object keys to be enclosed in quotes.

Instead of manually creating the JSON response, you can utilize json_encode() function to handle it automatically. Here's an example:

<?php
$conn = new mysqli("localhost", "root", "xxxx", "guestbook"); 
$stmt = $conn->prepare('SELECT title, content, author, email, ip FROM lyb limit 2');
$stmt->execute();
$stmt->bind_result($title, $content, $author, $email, $ip);
$result = [];
while ($stmt->fetch()) {
    $result[] = [
        'title'   => $title,
        'content' => $content,
        'author'  => $author,
        'email'   => $email,
        'ip'      => $ip
    ];
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($result);
exit;

You're not obligated to use prepare() and bind_result(); it's just my personal preference while dealing with MySQLi.

This block of code will generate a result similar to this:

[
  {
    "title": "welcome1",
    "content": "welcome1",
    "author": "welcome1",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="daadbfb6b9b5b7bfeb9aaeb5b7f4b9b5b7">[email protected]</a>",
    "ip": "59.51.24.37"
  },
  {
    "title": "welcome2",
    "content": "welcome2",
    "author": "welcome2",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc8b99909f939199cebc889391d29f9391">[email protected]</a>",
    "ip": "59.51.24.38"
  }
]

Answer №2

Your PHP code contains several errors that need to be addressed.

To properly handle server-side operations in PHP, follow these steps:

Filename: test-json.php

  1. Retrieve records from the database.

  2. Create an array (named $data in the provided code) with the retrieved records.

  3. Encode this array in JSON format and output the result.

For handling client-side operations (JavaScript), follow these steps:

  1. Send an AJAX request to the test-json.php file.

  2. If the request is successful, parse the returned JSON data and generate HTML content to be appended to a table.

  3. Append the generated HTML to the table for better performance by accessing the DOM only once per AJAX request.

To implement the solution correctly, refer to the following code snippets:

PHP Code - Filename: test-json.php:

<?php
// Utilize specific column names in the SELECT query instead of '*'.
$conn = new MySQLi("localhost", "root", "xxxx", "guestbook");

$result = $conn->query("SELECT `title`, `content`, `author`, `email`, `ip` FROM `lyb` LIMIT 2");

$data = [];

while($row = $result->fetch_assoc()) {
  $data[] = [
    'title'   => $row['title'],
    'content' => $row['content'],
    'author'  => $row['author'],
    'email'   => $row['email'],
    'ip'      => $row['ip']
  ];
}

header('Content-type: application/json; charset=utf-8');
echo json_encode($data);

JavaScript Code:

$(function(){
    $.getJSON("test-json.php", function(data) {
        var html = '';
        $.each(data,function(key, value){
            html += "<tr><td>" + value.title + "</td>"    +
                        "<td>"  + value.content  + "</td>" +
                        "<td>"  + value.author  + "</td>"  +
                        "<td>"  + value.email  + "</td>"   +
                        "<td>"  + value.ip  + "</td></tr>";

        });
        $("#disp").append(html);
    });
});

Explore more about the json_encode function here.

These instructions should help you progress further.

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

Tips on boosting the speed and user-friendliness of your AJAX/REST application

Exploring the Essential Requirements of an Application I am currently developing a comprehensive application using AngularJS (but it could be any framework). This application interacts with a server built on Google App Engine through REST technology. Th ...

A guide to showcasing a subcategory within a parent category through ajax

I have a custom module that displays the root category. When I click on a specific category, I want to use Ajax to display its subcategories with checkboxes. The code provided above retrieves all root categories: <?php $parentCategoryId = Mage::app() ...

Is there a way to modify the state of my spans by utilizing onMouseHover functionality?

I am currently updating the state of my span by using document.getElementById('heart').innerHTML = 'favorite'; Do you have a more efficient method for achieving this? If so, please share your solution with me. Below is my code snippet. ...

It is my goal to populate the array with numbers while avoiding any duplicate entries

I am currently facing an issue with my code as it is returning a length of 0 instead of the expected result of 5 after excluding duplicates from the array. I have a feeling that there might be something missing in my code, but I just can't seem to fig ...

Jest - experiencing intermittent test failures on initial run, yet succeeding on subsequent runs

Writing tests with jest and supertest npm on a node server has been a challenge for me. When I try to run all the tests together, some of them fail inexplicably: https://i.sstatic.net/TWDVp.png However, if I selectively run only the failed tests in the t ...

Efficiently reducing the size of a CSS selector string with javascript

Is there a library that already performs this function? I've only been able to find online tools. The reason I am interested in accomplishing this task using JavaScript is because I need to ensure that the strings a > b, a and a> b,a are conside ...

Is the string data in JSON format stored in SharedPreferences globally saved?

What is the best practice for storing global data in Android - saving it as a JSON format String and accessing it through SharedPreferences when needed? ...

What is the best way to change a NSString from JSON into an NSDictionary?

FINAL EDIT WITH THE SOLUTION: A resolution to the issue is presented below: -(void) attackLawyers { lawyers = [[[NSArray alloc] init] autorelease]; NSLog(@"%@", userReceived); NSString *myRequestString = [NSString stringWithFormat:@"user=%@", userRece ...

When trying to use bootbox.confirm within a dynamically loaded AJAX div, the modal unexpectedly opens and

I have implemented bootbox into my project, which was downloaded from . user_update.php is being loaded in a div within users.php using ajax functionality. Within user_update.php, there is a JavaScript function called validateForm(). Right after the functi ...

Is it possible for me to create a list in alphabetical order beginning with the letter B instead of A

My task involves creating a summary of locations using the Google Maps API. The map displays letters corresponding to different waypoints, and I have a separate <div> containing all the route information. Currently, I have the route information stru ...

Django views are not receiving multiselect data from Ajax requests

As a newcomer to Django, I am still learning the ropes. One challenge I am facing involves a multiselect list on my webpage. I need to send the selected items to my views for processing, and I attempted to accomplish this using Ajax. However, it seems that ...

Top method for implementing dynamic routing in Express.js (node.js)

I am currently in the process of developing a straightforward CMS using express.js that can dynamically generate routes based on JSON data retrieved from a database. Here is an example of the JSON structure: pagesfromdb = { home = { paths = [& ...

Clicking the button in Angular should trigger a series of functions to be

It seems like I'm struggling with a simple question due to my lack of experience in this area. Any guidance or help would be greatly appreciated. I have a button that should trigger multiple functions when clicked, all defined in the same ts file. Wh ...

Is there a way to automatically increase a value by clicking on it?

Check out this code snippet I'm working with: let funds = document.createElement('funds') funds.style.color = 'green' funds.style.textAlign = 'center' funds.style.fontSize = '50px' funds.style.backgroundCol ...

Randomize.js feature following the completion of an asynchronous request

I recently started using a library called Shuffle, which can be found at . It works well for me, but I am currently facing an issue with implementing a load more button to load additional images. The functionality is based on Ajax, however, after making t ...

Error: A semicolon is required before the statement in an HTML select tag

I am struggling with the code below in my java script: var i = 2; $(".addmore").on('click', function () { count = $('table tr').length; var data = "<tr><td><input type='c ...

Stop IE from caching AJAX requests when using the POST method

What methods can be used to prevent Internet Explorer from caching server requests? I attempted setting ("Cache-Control: no-cache) in the https response object, but IE continues to cache my request data. Here are the project details: When I log in to my ...

Avoiding double entries in the shopping list using DOM selectors in JavaScript

I have been struggling with preventing duplicate items from being added to a shopping list that I created. Even though I thought the code below would solve the issue, it hasn't been effective so far. My expectation was for the JavaScript code to acces ...

When utilizing AjaxHelper for fetching a partial view, the included data remains constant each time

We are utilizing ASP.NET MVC 5's AjaxHelper and Ajax.BeginForm to trigger a partial view request. This request necessitates specific JSON data for updating a map control. The rendering of the view is functioning correctly (the table body gets replace ...

Error encountered when attempting to initiate a second screenshare on Chrome due to an invalid state

I am interested in utilizing Screensharing in Chrome. After following a guide and creating an extension to access the deviceId for getUserMedia, I was able to successfully start streaming my screen. However, when I attempted to stop the stream using the pr ...