Using AngularJS to work with JSON data directly allows for seamless integration

My goal is to generate charts by utilizing data from MySQL within my JS file.

The process involves:

  • Fetching data in my JS script by calling my PHP file.
  • Successfully establishing a connection (PHP).
  • Converting the data into JSON format.
  • Retrieving the transformed data back in my JS file.
  • Rendering and displaying the data on my HTML page/file.

Here is an example snippet of how I am displaying the data using AngularJS:

`<div ng-repeat="x in users" align="center">
          <div class="col-md-4" >
            <div class="showProfile">
               {{x.TotalCall}}
            </div>
           </div>
         </div>`

This is how my PHP code looks like:

    <?php

  $dbhost="localhost";
    $dbuser="root";
    $dbpass="";
    $dbname="callstats";
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $query = $dbh->query("SELECT extension, COUNT(*) AS TotalCall, COUNT(CASE WHEN billsec >= 20 THEN billsec END) AS 'moreThanTwenty' FROM pbx GROUP BY extension");
  $query = $query->fetchAll(PDO::FETCH_ASSOC);
  $myJson = json_encode($query);
  echo "{\"records\":".$myJson."}";

?>

And this is how my AngularJS file is structured:

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
        $http.get("php/DBbitrix.php")
        .then(function(response) {
          $scope.users = response.data.records;
        });

    // additional charting logic goes here

});

If the data for the pieChart is [20,50,60,80,100], the visualization will be successful. I aim to use the values stored in the TotalCall table of my database in the "data : []" section.

Despite encountering challenges for the past few days, I have attempted various solutions such as using angular.foreach. However, incorporating the JSON data directly into my JS file remains elusive.

I've made efforts to inspect and log the values in the console with no luck:

var users = $scope.users;
console.log(users);
// additional console logs

Regrettably, the value returned is consistently "undefined," leaving me unable to access the desired data. As a learner of English, please forgive any errors in this post, as it marks my first contribution on Stackoverflow.

Answer №1

console.log("{\"data\":".$myJson."}")

You are not getting a JSON object directly. What you receive is a string that reflects a JSON object. This means you will need to parse it like this:

.then(function(result) {
    var myJson = JSON.parse(result)
    $scope.data = myJson.records;
});

Answer №2

Appreciate your assistance.

The initial parse was crucial in addressing the issue. I made a minor error by misplacing the "});".

Sharing my solution in hopes that it benefits others!

Using AngularJS :

//pie
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $http) {
    $http.get("php/DBbitrix.php")
    .then(function(response) {
    var myJson = jQuery.parseJSON(JSON.stringify(response));

    $scope.users = myJson.data.records;
    $scope.data = [];
    for (var i = 0;i < $scope.users.length; i++) {
    $scope.data.push($scope.users[i].TotalCall);
    }

    //pie
    var ctxP = document.getElementById("pieChart").getContext('2d');
    var myPieChart = new Chart(ctxP, {
        type: 'pie',
        data: {
            labels: ["Red", "Green", "Yellow", "Grey", "Dark Grey","Red", "Green", "Yellow", "Grey", "Dark Grey","Red", "Green", "Yellow", "Grey", "Dark Grey"],
            datasets: [
                {
                    data : $scope.data,

                    backgroundColor: ["#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360","#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360","#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360"],
                    hoverBackgroundColor: ["#FF5A5E", "#5AD3D1", "#FFC870", "#A8B3C5", "#616774","#FF5A5E", "#5AD3D1", "#FFC870", "#A8B3C5", "#616774","#FF5A5E", "#5AD3D1", "#FFC870", "#A8B3C5", "#616774"]
                }
            ]
        },
        options: {
            responsive: true
        }
    });
});
});

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

Using raphaeljs and freetransform in conjunction with clip-path

Currently, I am utilizing Raphael along with Elberts FreeTransform Plugin. You can view my progress so far by visiting MyWork The issue arises when I attempt to translate or rotate the set of rectangles within my clip path. Once rotated or translated, it ...

What is the best way to access and read data from the object I retrieved from Parse.com?

I'm having trouble accessing the values I need after retrieving an object in Angular JS. Here is my setup: HTML <h1>{{myTrip[0].attributes.title}}</h1> <br/> <p>{{myTrip[0].attributes.descr}}</p> JS: var ...

Utilizing Vue JS to pass props from various routes to a shared component

Currently, I am working on developing a menu application using Vue JS. As per the advice given to me, it is suggested that I only need to use one component if the styling remains consistent throughout. This implies that I need to incorporate dynamic data i ...

Launching an Electron app with an Express server in Node.js

I have a program using Express/Nodejs for the backend, and AngularJS (I know it's old) for the frontend. I'm attempting to display this program in an Electron window. After some searching, here's what I've found: main.js const {Browser ...

What is the best way to display the panel during a postback?

I have a group with two radio buttons labeled purchase and expenses. When the purchase radio button is clicked, the panelpurchase will be displayed, and similarly, the panelexpense will show for the expenses radio button. Check out the image of the output ...

The React.js component search test encounters errors in locating components

I have been working on a React app that utilizes Redux and React-router. I am currently writing tests using React TestUtils, and I encountered an issue with the following test results: The first expect statement is successful: expect(nav).to.have.length(1) ...

Unexplainable space or padding issue detected in OwlCarousel grid gallery

There seems to be an unusual gap or margin at the bottom of each row section in this portfolio grid gallery that's running in OwlCarousel. You can view an example here. https://i.stack.imgur.com/NHOBd.png I've spent a lot of time trying to solv ...

What steps should be taken to complete the compilation of an element when the directive specifies terminal: true?

Check out the code here. In an attempt to develop a directive that re-arranges its child elements, a simple ng-transclude won't do as I need to place some child elements in different locations within the template. The key seems to be setting terminal ...

Error in whatsapp-web.js: Unable to access properties of an unidentified object (reading 'default')

As I followed the step-by-step guide on how to use whatsapp-web.js, I encountered an issue. Here is the link to the guide const { Client } = require('whatsapp-web.js'); const qrcode = require('qrcode-terminal'); const client = new Cl ...

AngularJS Dropdown in ASP.NET MVC 3

I want to create a DropDownList using @Html.DropDownList and connect it with AngularJS. Below is the code snippet: @Html.DropDownList("LessonID", (SelectList)ViewBag.LessonList, "choose one", new { ng_model = "LessonID" }) Here's an example of ...

Dealing with PhantomJS: Tackling the Challenge of XMLHttpRequest Exception 101 Error

As a newcomer to JavaScript and PhantomJS, I have been encountering an issue when running myfile.js (which involves for loops) with the command phantomjs myfile.js. It consistently throws the error: NETWORK_ERR: XMLHttpRequest Exception 101: A network err ...

Utilize data obtained from an ajax request located in a separate file, then apply it within a local function

Seeking assistance in navigating me towards the right path or identifying my errors. Pardon if my explanation is unclear, please be gentle! Currently, I am engaged in developing a function that executes an ajax call with a dynamically generated URL. The o ...

Having trouble getting my Node.js application to deploy properly on Heroku

Check out my repository here: https://github.com/jacklemasters/tech-blog Although the app runs smoothly on my local machine, I can't figure out why it's not working on Heroku. I've tried moving the code completely and creating a new reposit ...

AngularJS provides the ability to use cookies when working with an EventSource

I'm exploring the idea of using EventSource to send server events to the client, but I want the client to be able to distinguish itself so it only receives its own events. I've been attempting to utilize cookies for this purpose, but for some rea ...

Retrieving an assortment of objects from a database and showcasing them using React

Attempting to retrieve an array of objects led me to this issue. Please excuse the messy code, I am still learning. export class App extends Component { state ={ character:[] } componentDidMount(){ fetch('https://swapi.dev/api/people/ ...

Guide on setting the HTML img src value with AR.ImageResource in ARchitectBrowser.html while utilizing the Wikitude SDK for iOS

I am currently customizing the ARchitectBrowser.html file provided by the Wikitude SDK for iOS and I am interested in finding a way to directly insert an image set in AR.ImageResource. bubbleImage = new AR.ImageResource("http://graph.facebook.com/" + json ...

Developing a JSON structure from a series of lists

var data = [ [ "default_PROJECT", "Allow", "Connect", "Allow", "AddComment", "Allow", "Write", "Allow", "ViewComments", "Allow", "ExportData", "Allow", ...

Utilizing PATCH for partial updates: Decoding JSON information for SQL modifications

I have been working on implementing the 'PATCH' method on the server-side to allow for partial updates to my resources. Without directly exposing my SQL database schema in JSON requests/responses, meaning there is a separate mapping between keys ...

Using Javascript to select a radio button in a form depending on the value entered in a text box

I have a form that interacts with a Google Sheet to insert and retrieve data. For instance, the form contains two radio buttons: <input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck" value="1" onchange="RadioValInsert ()"/> < ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...