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

Scroll the content of a div to the bottom using JavaScript

I'm facing a situation with my code: function scrollme(){ dh=document.body.scrollHeight ch=document.body.clientHeight if(dh>ch){ moveme=dh-ch window.scrollTo(0,moveme) } } However, I am looking for a way to make it scroll only within a specific d ...

When a child component is updated, React does not automatically re-render

My goal is to pass the email from the SigninForm back to the App component and trigger a re-render when the email is updated. I attempted to follow the structure outlined in a previous question on Stack Overflow, but unfortunately, I couldn't get the ...

Error encountered while attempting to save a Mongoose post on Heroku, although it is successful

My aim is to post to my MongoDB Atlas database using node, express, mongoose, and Heroku. While a Postman POST request with Raw JSON body: { "title": "heroku post", "description": "post me plsssss" } works f ...

It's time to wrap up the session with some old "cookies" and a closing function

Would like the message to only display once after clicking the "Cookies" button. Once the user accepts cookies, they should be stored on their device for a set period of time. Your assistance is greatly appreciated. :) Below is the html and js code: $(do ...

Retrieve the value of a variable in a Bootstrap modal using Jade

I am looking to accomplish the following: On my Jade page, I have a for-loop that generates a list of items. Each item has some information displayed through Jade variables and a delete button. When this delete button is clicked, I want a Bootstrap Modal ...

The attention remains fixed at the top of the page

I have implemented an update panel along with pagination links using a repeater control at the bottom of my page. However, I am encountering an issue where clicking on the pagination links does not bring the page to the top. I attempted to use the followin ...

The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well. This is the scenario. When running the following code: class Person { @IsValueIn(['PETER', ' ...

Class component proceeding without waiting for function completion

My function, getactivity(), pulls and sorts data from an API and returns the sorted data in answer1 format. However, I am facing a problem where whenever I run the function to retrieve the data, it keeps returning nothing. Here is the full code: import Re ...

What is the speed difference between calling functions from require's cache in Node.js and functions in the global scope?

Let's imagine a scenario where we have two files: external.js and main.js. // external.js //create a print function that is accessible globally module.exports.print = function(text) { console.log(text) } Now let's take a look at main.js: ...

Encountered an issue with reading the property childnotes of null during data retrieval using ajax in PHP

Hello, I am encountering an error while trying to fetch data using ajax. The error message is "Cannot read property 'childNodes' of null". Can anyone help me identify what might be wrong with my code? I have created a form to search for data with ...

Tips on comparing a string against an object's value

I need to compare the key values of an object with the strings yes or no. I am encountering difficulties in achieving this comparison and updating radio buttons accordingly based on the comparison. Here is the code snippet: const screenJson = { Managem ...

Is it possible to display a thumbnail image in a separate full-sized window by using CSS or JavaScript?

I am currently utilizing a program called WebWorks 2020.1 that automatically creates <img> tags from my FrameMaker source input when published to DHTML. Unfortunately, I do not have the ability to directly modify the HTML <img> or <a> tag ...

include a button next to the input field

As you reduce the browser window size, you may notice a different layout designed specifically for iPhone. One question that arises is how to add a button next to the search text box dynamically using JavaScript. The issue at hand is that the text box is b ...

Changing a 64-bit Steam ID to a 32-bit account ID

Is there a way to convert a 64-bit Steam ID to a 32-bit account ID in Node.js? According to Steam, you should take the first 32 bits of the number, but how exactly can this be done in Node? Would using BigNumber be necessary to handle the 64-bit integer? ...

Using canvas to smoothly transition an object from one point to another along a curved path

As a beginner in working with canvas, I am facing a challenge of moving an object from one fixed coordinate to another using an arc. While referring to the code example of a solar system on https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutori ...

Is it possible to submit a form through a JavaScript hotkey?

Here's the current code that I'm working with: <select tabindex="2" id="resolvedformsel" name="resolved"> <option selected="selected" value="yes">resolved</option> <option value="no">not resolved</option> ...

Move the dist folder to the libs directory using webpack

I am interested in achieving the following task: After successfully using gulp for copying libraries, I added the below code to my tasks: gulp.task('copy:libs', function() { return gulp .src(npmdist(), { base: paths.base.node.dir }) . ...

Guide on how to restrict specific days and dates in MUI React datepicker using a JSON array

I am working on a Laravel application that generates a JSON response containing dates and days of the week that need to be disabled in the datepicker. For instance, here is an example of my datesOff constant when I log it: ['2022-05-08', '2 ...

Creating a polyBezier or polyCurve with Canvas HTML: a step-by-step guide

Looking to connect several points with a curve rather than just a straight line. I attempted using the lineTo() and bezierCurveTo() methods to draw the points. Is there anyone who can assist me in solving this dilemma? Perhaps there is a different approac ...

Unable to retrieve link text following readFile function. Selector functions properly in Chrome console

My goal is to extract hyperlink text. Using the google chrome console with my selector, I am able to retrieve a list of 15 link texts as desired. However, when I execute my code with the same selector, the el.text returns undefined in console.log while th ...