Unable to retrieve JSON data from a PHP file hosted on the server

I have a server-side database with a table called "customers" and a column named "names". My goal is to send a request to the server asking for the first two records in the "customers" table. However, when I execute the program, the browser does not display the records and instead shows them as undefined. Refer to the image below for more details.

https://i.stack.imgur.com/dkQio.jpg

PHP File:

<?php

header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);

$conn = new mysqli("127.0.0.1", "abc", "def", "mydatabase");
$result = $conn->query("SELECT names FROM " . $obj->table . " LIMIT " . $obj->limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($outp);
?>

HTML File:

<p id="demo"></p>

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":2 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        for (x in myObj) {
            txt += myObj[x].name + "<br>";
        }
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("GET", "demo_file.php?x=" + dbParam, true);
xmlhttp.send();

</script>

Answer №1

It is important to use the names instead of name when referencing objects in a JavaScript loop, especially when dealing with select queries where both the columns and results contain the names property.

<p id="demo"></p>

<script>
    var obj, dbParam, xmlhttp, myObj, x, txt = "";
    obj = { "table":"customers", "limit":2 };
    dbParam = JSON.stringify(obj);
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myObj = JSON.parse(this.responseText);
            console.log(myObj)
            for (x in myObj) {
                txt += myObj[x].names + "<br>";
            }
            document.getElementById("demo").innerHTML = txt;
        }
    };
    xmlhttp.open("GET", "demo_file.php?x=" + dbParam, true);
    xmlhttp.send();

</script>

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

Choose the minimum price from the JSON response of the API

I have made an AJAX request to an API and received the following JSON response below. I am trying to extract the lowest 'MinPrice' from the 'Quotes' data but finding it challenging to determine the best approach. One method I am consid ...

Find the average value of an array containing objects

Imagine I have an array of objects like this: const BookDetails = [ { bookName: 'Harry Pottar', readingTime: 10663 }, { bookName: 'Harry Pottar', readingTime: 10986 }, { bookName: 'kaptura Tech', readingTime: 7034 } ] I ...

What is the best way to direct visitors who are not logged in to the Login page in Wordpress?

I have been struggling to find an answer to this question for my specific case with the current version of Wordpress. I have a website running on Wordpress with Buddypress installed. My goal is to restrict non-logged in users to only see the wp-login.php ...

Show live data in JQgrid on Codeigniter platform

I'm currently working on a project using CodeIgniter that involves implementing a JQgrid table to display data. While I am able to retrieve the data from the database, I have encountered difficulties in displaying it within the JQgrid itself. However, ...

What is the method for utilizing underscores in Visual Studio Code without the need to "enable" them beforehand?

I attempted to utilize underscore in Visual Studio Code and found that it only works if I include this line of code at the beginning: var _ = require('underscore'); The output functions properly with this code in place. However, if I remove it, ...

jQuery Autocomplete - Showing array of options upon selecting input field in Internet Explorer

After encountering an issue with the autocomplete feature in a web application, I posted a question on Stack Overflow. The provided answer solved the problem in Chrome, but unfortunately, it did not work in Internet Explorer 8 or 9, and possibly earlier ve ...

What is the process for integrating three.js code manually into an iframe?

I recently posted a question on Stack Overflow inquiring about how to input code into an iframe without using a file or URL. While I was successful with simple cases like <h1>Hello World</h1>, my ultimate goal is to integrate three.js into thes ...

Instructions on how to eliminate the minutes button from Material UI datetime picker

I'm currently working on customizing a datetimepicker from materialUI in ReactJS. My goal is to prevent the user from seeing or selecting minutes in the picker interface. Despite setting the views prop to include only year, month, date, and hours, use ...

Enhancing code branch coverage using Istanbul

The code snippet provided has a branch coverage of only 50% (refer to the coverage report below). I am unsure how to enhance this as there are no if statements present. I suspect that Istanbul must utilize some form of measurement that I have yet to grasp ...

Implementing JavaScript: Grouping JSON Response by Date and Category in a Table

The API response provided below contains sample data. {"success":true,"transaction":[{"_id":"58efd5717ddda769f26793fc","transId":"Exp/04-17/17","trpId":"Trav/dfsd/04-17/12","tripId":"58efd4dc7ddda769f26793f8","userId":"58ac19eaec1e7e4628be6f01","expenseHe ...

How can the Jquery UI Datepicker value be automatically set upon redirecting to this page?

When I submit a form and an error occurs, the value selected in the datepicker is not retained. The datepicker field remains empty. How is this possible? <html> <head> <script type="text/javascript" >. $(function() { ...

Tips for storing extra columns in a polymorphic morphable model in Laravel version 7

Explore a many-to-many polymorphic relationship example from the Laravel documentation website. posts id - integer name - string videos id - integer name - string tags id - integer name - string taggables tag_id - integer ...

Error encountered when trying to load Ajax script

As a beginner in the learning process, my code may appear messy. I am currently wrapping up my second project, which is a photo viewer. On the main page, there is a navigation system that loads different sections of the website using ajax. Since this proje ...

The vue-croppa component is showing unusual behavior, with an error message stating "Failed to mount component: template or render function not

I recently tried utilizing vue-croppa for image cropping in my project. I installed it using the npm package manager with the command: npm install --save vue-croppa However, when attempting to implement it as usual: import Croppa from 'vue-croppa&a ...

Designing a database table to accommodate numerous columns for importing data from a spreadsheet, with the capability to expand as

One of my clients has a need to regularly import a large spreadsheet of data, which seems quite extensive to me. The file currently contains about 200 rows and 41 columns. The first two columns serve as identifiers - one is an ID while the other provides ...

`I'm encountering issues when trying to pass an array through localStorage into a new array`

This is a complex and detailed question that I am struggling to find a solution for. Despite using deprecated mysql due to hosting limitations, the problem lies elsewhere. Part 1 involves dataLoader.php, which queries the database and retrieves posx and p ...

Using AJAX to dynamically update content via HTTP requests

Why do I keep seeing "loading..." instead of the content from data.php? xmlhttp = new XMLHttpRequest(); function fetchData () { xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState = 4 && xmlhttp.status == 20 ...

Adding a fresh element to an array in Angular 4 using an observable

I am currently working on a page that showcases a list of locations, with the ability to click on each location and display the corresponding assets. Here is how I have structured the template: <li *ngFor="let location of locations" (click)="se ...

The event listener function is not functioning properly on images generated by JavaScript

I'm currently working on placing multiple images on a grid in the center of the page and would like to include a function that triggers when each individual image is clicked. The images are dynamically created using JavaScript and inserted into the do ...

What could be causing the issue of the title in req.body to display as 'undefined'?

I am currently learning about NODE JS and practicing working with POST forms from PUG to a NODE JS server. I am facing an issue where the submission input is coming back as 'undefined' when I submit a form from the web browser. In the code snipp ...