Incorporating database row data into JavaScript objects: a guide

Here's a question that has me stumped and seeking help.

Following an ajax send request, I utilized this php code to retrieve all the rows and columns from my database:

$sql = "SELECT * FROM categories";
$result=$conn->query($sql);  
$arr = $result->fetch_all(MYSQLI_ASSOC);


print_r($arr)

This resulted in the following output:

Array ( [0] => Array ( [cat_id] => 1 [cat_name] => Friends [checkbox] => checked ) [1] => Array ( [cat_id] => 2 [cat_name] => Favourites [checkbox] => checked ) [2] => Array ( [cat_id] => 3 [cat_name] => Drink [checkbox] => checked ) [3] => Array ( [cat_id] => 4 [cat_name] => Food [checkbox] => checked )
<br>

I then encoded it using:

echo json_encode($result);

Next, I fetched the data into a JavaScript variable with the following code:

result = Request.responseText;
var categories = JSON && JSON.parse(result) || $.parseJSON(result);

The challenge now is how to access the rows of data stored in the 'categories' variable. Upon verifying that the JSON encoding was successful by confirming that 'categories' is now of type [Object object], I am unsure of what steps to take next.

Answer №1

Categories should always be in the form of an array. To confirm this, you can execute the following code:

console.log(categories.length);

If the above line prints out the number of elements in the array as expected, you can then proceed to iterate over each row using a basic for loop:

for (var i = 0; i < categories.length; ++i) {
    console.log(categories[i].cat_name);
}

Alternatively, you may also utilize the Array.forEach method along with a callback function for iteration:

categories.forEach(function(category) {
    console.log(category.cat_id + ' = ' + category.cat_name);
});

Answer №2

After hours of struggling with this yesterday, I woke up this morning and managed to solve it in just 15 minutes.

echo json_encode($result); //wrong variable

The correct code should be:

echo json.encode($arr); // correct variable 

I've learned my lesson: sometimes all you need is a good night's sleep!

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

When trying to append in jQuery, the error "JQuery V[g].exec is not a

Attempting to create a script that adds a table to a div within the website using the following function: function generateTable(container, data) { var table = $("<table/>"); $.each(data, function (rowIndex, r) { var row = $("<tr/>"); ...

Unable to proceed due to lint errors; after conducting research, the issue still remains

I'm still getting the hang of tslint and typescript. The error I'm encountering has me stumped. Can someone guide me on resolving it? I've searched extensively but haven't been able to find a solution. Sharing my code snippet below. (n ...

Exploring TingoDB: Trouble encountered when passing global variable to insert operation

During my testing and benchmarking of several embedded databases using node.js, I have encountered an interesting issue with TingoDB. Does anyone have insight into why the following code snippet works as expected: var test = { hello:'world' }; f ...

The inner workings of Virtual DOM in React and Vue disclosed

I am a student experimenting with creating my own Virtual DOM for a college project in JavaScript, keeping it simple without advanced features like props or events found in popular frameworks like React and Vue. I'm curious about code splitting. If I ...

The instance does not have a definition for the property or method "foo" that was referenced during rendering

[Vue warn]: Property or method "modelInfo" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. Whenever I ...

What is the best way to limit the number of items shown in a cart dropdown using JavaScript

I have a shopping cart feature added to my ecommerce web app. Within the header, there is an icon of a cart. When clicked, a dropdown appears showing the items added to the cart. However, if I have 10 items in the cart, the dropdown becomes too lengthy to ...

Focusing on the combination of Phonegap, Angular JS, and Onsen for app development

We are working on developing an app using PhoneGap, Angular JS, and Onsen. One issue we are facing is that we are unable to center the header in a modal. The code snippet is provided below: <ons-modal var="modalVariable"> <ons-navigator var"de ...

I encountered a problem in Javascript where I was unable to get the video.getCurrentTime() function to display the current time of

While everything else in my code is running smoothly with setInterval, there seems to be an issue with video.getCurrentTime() not displaying in the div id = "test" when the video is playing. I've been trying to figure out why this is happening. Here&a ...

Leverage the hidden glitch lurking within Vue

While working with SCSS in vue-cli3, I encountered a strange bug where using /deep/ would result in errors that I prefer not to deal with. Code Running Environment: vue-cli3 + vant + scss CSS: /deep/ .van-tabs__content.van-tabs__content--animated, .va ...

Removing the navigation button from the hamburger menu

I am working on creating a semi-progressive top navigation bar. For the mobile viewport, the navigation bar will only display the logo and a hamburger button. When the button is clicked, various navigation menu options as well as the Log In and Sign Up bu ...

Implementing a delay between two div elements using jQuery

I have two Divs with the class "sliced", each containing three images with the class "tile". When I animate using jQuery, I am unable to add a delay between the "sliced" classes. However, I have successfully added a delay between the "tile" classes. index ...

What is a way to activate the onSelectionChange event only when the cursor moves without any changes in the input?

In my React Native app, I have a use case where I want to implement mentions. This requires calling a function on the onSelectionChange event only when the text in the input remains unchanged but the caret position has moved. Currently, the onSelectionCha ...

Is there a way in Javascript to apply quotation marks to each value within an array individually?

I've created a function that retrieves and displays values from a CSV file. Here is the code for the function: var IDArr = []; var fileInput = document.getElementById("csv"); readFile = function() { console.log("file uploaded") var reader = new ...

Importing the Monday view in React - A step-by-step guide

I am interested in incorporating one of my Monday boards into my React component. Here is a snippet of the code: import React from 'react' import useI18n from 'hooks/useI18n' import Page from 'components/layout/Page' const Ro ...

Adjusting the size of a Video/Image Slider to perfectly fit the screen dimensions (both width and height

I have been using a slider code to display my images and videos. The code can be found here: Code:https://codepen.io/1wdtv/pen/jbjZeb The issue I am facing is that the slider is only responsive in terms of width. This means that when resizing the browser ...

Using VueJS: accessing this.$store within component data property

I am interested in utilizing the data from my Vuex store in both my app and template. My Vuex store: var Vue = require('vue'); var Vuex = require('vuex'); Vue.use(Vuex) let store = new Vuex.Store({ state: { user: ...

Updating variable storage in React components

This is a project built with Next.js and React. Below is the folder structure: components > Navbar.js pages > index.js (/ route)(includes Navbar) > submitCollection.js (/submitCollection)(includes Navbar) The goal is to allow users to inpu ...

Retrieving the value of a child in JSON

I have encountered this JSON structure and I am interested in extracting the value of "resource_uri" which is "/api/v1/client/2/". My implementation revolves around Backbone/javascript. Unfortunately, using json['resource_uri'] does not produce ...

Exciting Update: Next.js V13 revalidate not triggering post router.push

Currently using Next.js version 13 for app routing, I've encountered an issue with the revalidate feature not triggering after a router.push call. Within my project, users have the ability to create blog posts on the /blog/create page. Once a post is ...

Android List View - Navigate to a website when clicked

Apologies if this question sounds inexperienced, but I am not very familiar with Android. I have a MainActivity.Java file that uses JSON data retrieved from a server to populate a TextView. The parameters received from the server include id, username, mes ...